--- /dev/null
+#!/bin/sh
+#
+# chroot_wrapper.sh - simplistic wrapper to make chroot more practical
+#
+# Copyright (C) 2016 Antonio Ospite <ao2@ao2.it>
+#
+# This program is free software. It comes without any warranty, to
+# the extent permitted by applicable law. You can redistribute it
+# and/or modify it under the terms of the Do What The Fuck You Want
+# To Public License, Version 2, as published by Sam Hocevar. See
+# http://sam.zoy.org/wtfpl/COPYING for more details.
+
+set -e
+
+[ "x$1" = "x" ] && { echo "usage: $(basename $0) <NEWROOT> [<COMMAND>]" 1>&2; exit 1; }
+
+NEWROOT="$1"
+shift
+
+COMMAND="$@"
+[ "x$COMMAND" = "x" ] && COMMAND="/bin/bash"
+
+[ "$(id -u)" = "0" ] || { echo "Run this script as root." 1>&2; exit 1; }
+
+_mount_prereq() {
+ mount --bind /dev ${NEWROOT}/dev
+ mount --bind /dev/pts ${NEWROOT}/dev/pts
+ mount --bind /proc ${NEWROOT}/proc
+ mount --bind /sys ${NEWROOT}/sys
+ mount --bind /run ${NEWROOT}/run
+ mount --bind /tmp ${NEWROOT}/tmp
+}
+
+_umount_prereq()
+{
+ umount ${NEWROOT}/tmp || :
+ umount ${NEWROOT}/run || :
+ umount ${NEWROOT}/sys || :
+ umount ${NEWROOT}/proc || :
+ umount ${NEWROOT}/dev/pts || :
+ umount ${NEWROOT}/dev || :
+}
+
+_mount_prereq
+trap '_umount_prereq' 0
+trap "exit 2" 1 2 3 15
+
+# Unshare the UTS namespace.
+# This ensures that the hostname change affects only the chrooted process.
+# WIthout "unshare --uts" the host system hostname would be changed too.
+# An alternative way would have been to use a tool like chname:
+# http://blog.marineau.org/post/46688543379/giving-chroot-its-own-hostname-chname
+unshare --uts chroot ${NEWROOT} /bin/bash -c "hostname -F /etc/hostname && exec ${COMMAND}"