#!/bin/bash
# vim: softtabstop=2 shiftwidth=2 expandtab

cleanup() {
  [ -n "${mountpoint}" ] && recursive_umount "${mountpoint}"
  mount_efivarfs

  trap - HUP INT QUIT ABRT EXIT
}

sources=(
  /lib/profiling-lib.sh
  /etc/zfsbootmenu.conf
  /lib/kmsg-log-lib.sh
  /lib/zfsbootmenu-core.sh
)

for src in "${sources[@]}"; do
  # shellcheck disable=SC1090
  source "${src}" >/dev/null 2>&1 || exit 1
done

unset src sources

selected="${1}"

zdebug "started with ${selected}"

[ -n "${selected}" ] || exit 0
pool="${selected%%/*}"

if ! is_snapshot "${selected}" && ! is_writable "${pool}" ; then
  if ! timed_prompt -d 10 \
    -e "Enter r/w chroot" \
    -r "Enter r/o chroot" \
    -p "Entering chroot in $( colorize yellow "%0.2d" ) seconds" ; then
      set_rw_pool "${pool}"
      CLEAR_SCREEN=1 load_key "${selected}"
  fi
fi

tput reset
tput clear

trap cleanup HUP INT QUIT ABRT EXIT

if ! mountpoint="$( allow_rw=yes mount_zfs "${selected}" )"; then
  zerror "failed to mount ${selected}"
  exit 1
fi

# Snapshots and read-only pools always produce read-only mounts
if is_snapshot "${selected}" || ! is_writable "${pool}"; then
  writemode="$( colorize green "read-only")"
  efivarmode="ro"
else
  writemode="$( colorize red "read/write")"
  efivarmode="rw"
fi

notices+=( "$(colorize white "*" ) $( colorize orange "${selected}" ) is mounted ${writemode}" )

zdebug "mounted ${selected} to ${mountpoint}"

mount -B /tmp "${mountpoint}/tmp"
mount -t proc proc "${mountpoint}/proc"
mount -t sysfs sys "${mountpoint}/sys"
mount -B /dev "${mountpoint}/dev"


if mount_efivarfs "${efivarmode}" ; then
  efivarfs="${mountpoint}/sys/firmware/efi/efivars"
  mount_efivarfs "${efivarmode}" "${efivarfs}"

  notices+=( "\n$(colorize white "*" ) $( colorize orange "efivarfs" ) is mounted ${writemode}" )
fi

# Not all /dev filesystems have /dev/pts
[ -d "${mountpoint}/dev/pts" ] && mount -t devpts pts "${mountpoint}/dev/pts"

_SHELL=
if [ -x "${mountpoint}/bin/bash" ] \
    && chroot "${mountpoint}" /bin/bash -c "exit 0" >/dev/null 2>&1 ; then
  _SHELL="/bin/bash"
  chroot_extra="--norc"
elif [ -x "${mountpoint}/bin/sh" ] \
    && chroot "${mountpoint}" /bin/sh -c "exit 0" >/dev/null 2>&1 ; then
  _SHELL="/bin/sh"
elif [ -x "${mountpoint}/bin/busybox" ] \
    && chroot "${mountpoint}" /bin/busybox sh -c "exit 0" >/dev/null 2>&1 ; then
  _SHELL="/bin/busybox"
  chroot_extra="sh"
fi

if [ -z "${_SHELL}" ]; then
  zerror "unable to test execute a shell in ${selected}"
  exit 1
fi

notices+=( "\n$(colorize white "*" ) $( colorize orange "/tmp" ) is mounted $( colorize red "read/write")" )
echo -e "${notices[*]}\n"

# will point to a script that doesn't exist in the chroot
unset PROMPT_COMMAND

# regardless of shell, set PS1
# shellcheck disable=SC2086
if ! env "PS1=\[\033[0;33m\]${selected}\[\033[0m\] \w > " chroot ${mountpoint} ${_SHELL} ${chroot_extra} ; then
  zdebug "chroot ${selected}:${_SHELL} returned code $?"
fi
