#!/bin/bash

shopt -s extglob

m4_include(common)

usage() {
  cat <<EOF
usage: ${0##*/} chroot-dir [command]

    -h                  Print this help message
    -u <user>[:group]   Specify non-root user and optional group to use

If 'command' is unspecified, ${0##*/} will launch /bin/bash.

Note that when using arch-chroot, the target chroot directory *should* be a
mountpoint. This ensures that tools such as pacman(8) or findmnt(8) have an
accurate hierarchy of the mounted filesystems within the chroot.

If your chroot target is not a mountpoint, you can bind mount the directory on
itself to make it a mountpoint, i.e. 'mount --bind /your/chroot /your/chroot'.

EOF
}

chroot_add_resolv_conf() {
  local chrootdir=$1 resolv_conf=$1/etc/resolv.conf

  [[ -e /etc/resolv.conf ]] || return 0

  # Handle resolv.conf as a symlink to somewhere else.
  if [[ -L $chrootdir/etc/resolv.conf ]]; then
    # readlink(1) should always give us *something* since we know at this point
    # it's a symlink. For simplicity, ignore the case of nested symlinks.
    resolv_conf=$(readlink "$chrootdir/etc/resolv.conf")
    if [[ $resolv_conf = /* ]]; then
      resolv_conf=$chrootdir$resolv_conf
    else
      resolv_conf=$chrootdir/etc/$resolv_conf
    fi

    # ensure file exists to bind mount over
    if [[ ! -f $resolv_conf ]]; then
      install -Dm644 /dev/null "$resolv_conf" || return 1
    fi
  elif [[ ! -e $chrootdir/etc/resolv.conf ]]; then
    # The chroot might not have a resolv.conf.
    return 0
  fi

  chroot_add_mount /etc/resolv.conf "$resolv_conf" --bind
}

while getopts ':hu:' flag; do
  case $flag in
    h)
      usage
      exit 0
      ;;
    u)
      userspec=$OPTARG
      ;;
    :)
      die '%s: option requires an argument -- '\''%s'\' "${0##*/}" "$OPTARG"
      ;;
    ?)
      die '%s: invalid option -- '\''%s'\' "${0##*/}" "$OPTARG"
      ;;
  esac
done
shift $(( OPTIND - 1 ))

(( EUID == 0 )) || die 'This script must be run with root privileges'
(( $# )) || die 'No chroot directory specified'
chrootdir=$1
shift

[[ -d $chrootdir ]] || die "Can't create chroot on non-directory %s" "$chrootdir"

if ! mountpoint -q "$chrootdir"; then
  warning "$chrootdir is not a mountpoint. This may have undesirable side effects."
fi

chroot_setup "$chrootdir" || die "failed to setup chroot %s" "$chrootdir"
chroot_add_resolv_conf "$chrootdir" || die "failed to setup resolv.conf"

chroot_args=()
[[ $userspec ]] && chroot_args+=(--userspec "$userspec")

SHELL=/bin/bash unshare --fork --pid chroot "${chroot_args[@]}" -- "$chrootdir" "$@"
