#!/bin/sh

set -e

usage() {
    echo "Usage: ${0##*/} /path/to/new/root [command ...]" >&2
    exit 1
}

if [ -z "$1" ]; then
    usage
fi

TARGET="$1"
shift

if [ ! -d "$TARGET" ]; then
    echo "Error: '$TARGET' is not a directory." >&2
    exit 1
fi

echo "Mounting virtual filesystems into $TARGET..."
mount -t proc proc "$TARGET/proc"
mount --bind /sys "$TARGET/sys"
mount --bind /dev "$TARGET/dev"
mount --bind /run "$TARGET/run"

if [ -d "$TARGET/dev/pts" ]; then
    mount -t devpts devpts "$TARGET/dev/pts"
fi

if [ -f /etc/resolv.conf ]; then
    if [ -f "$TARGET/etc/resolv.conf" ]; then
        cp "$TARGET/etc/resolv.conf" "$TARGET/etc/resolv.conf.bak"
    fi
    cp /etc/resolv.conf "$TARGET/etc/resolv.conf"
fi

cleanup() {
    echo "\nCleaning up mounts..."
    umount "$TARGET/dev/pts" 2>/dev/null || true
    umount "$TARGET/run"     2>/dev/null || true
    umount "$TARGET/dev"     2>/dev/null || true
    umount "$TARGET/sys"     2>/dev/null || true
    umount "$TARGET/proc"    2>/dev/null || true

    if [ -f "$TARGET/etc/resolv.conf.bak" ]; then
        mv "$TARGET/etc/resolv.conf.bak" "$TARGET/etc/resolv.conf"
    fi
}
trap cleanup EXIT INT TERM

if [ $# -eq 0 ]; then
    chroot "$TARGET" /bin/sh
else
    chroot "$TARGET" "$@"
fi
