#!/bin/sh
# arctic-chroot - enter an installed Arctic system with the kernel filesystems
# already bound, so package operations and bootloader work behave normally.
#
#   arctic-chroot                 enter /mnt
#   arctic-chroot /mnt            same, explicitly
#   arctic-chroot /mnt alpm list  run one command and come back out
#
# shellcheck shell=sh disable=SC2039

set -u

TARGET=${1:-/mnt}
case "$TARGET" in
-h|--help)
	sed -n '2,9p' "$0" | sed 's/^# \?//'
	exit 0 ;;
esac
[ -d "$TARGET" ] && shift 2>/dev/null || TARGET=/mnt

[ "$(id -u)" = "0" ] || { echo "Must be run as root." >&2; exit 1; }

[ -d "$TARGET" ] || { echo "arctic-chroot: $TARGET does not exist" >&2; exit 1; }
if [ ! -x "$TARGET/bin/sh" ] && [ ! -x "$TARGET/usr/bin/sh" ]; then
	echo "arctic-chroot: $TARGET does not look like a root filesystem" >&2
	echo "  (no /bin/sh - is it mounted?)" >&2
	exit 1
fi

MOUNTED=""

bind() {
	src=$1 dst="$TARGET$2" type=${3:-bind}
	mkdir -p "$dst" 2>/dev/null || return 0
	mountpoint -q "$dst" 2>/dev/null && return 0
	case "$type" in
	bind)  mount --bind "$src" "$dst" 2>/dev/null || return 0 ;;
	rbind) mount --rbind "$src" "$dst" 2>/dev/null || return 0
	       mount --make-rslave "$dst" 2>/dev/null || : ;;
	*)     mount -t "$type" "$type" "$dst" 2>/dev/null || return 0 ;;
	esac
	MOUNTED="$dst $MOUNTED"
}

cleanup() {
	# Deepest first, and lazily, so a busy mount does not wedge the exit.
	for m in $MOUNTED; do
		umount -l "$m" 2>/dev/null || :
	done
}
trap cleanup EXIT INT TERM

bind /proc /proc proc
bind /sys /sys sysfs
bind /dev /dev rbind
bind /run /run rbind
[ -d /sys/firmware/efi/efivars ] && bind /sys/firmware/efi/efivars /sys/firmware/efi/efivars

# Name resolution inside the chroot, without clobbering a real file.
if [ -f /etc/resolv.conf ] && [ ! -s "$TARGET/etc/resolv.conf" ]; then
	cp -f /etc/resolv.conf "$TARGET/etc/resolv.conf" 2>/dev/null || :
fi

SHELL_IN=/bin/zsh
[ -x "$TARGET$SHELL_IN" ] || SHELL_IN=/bin/sh

if [ $# -gt 0 ]; then
	chroot "$TARGET" "$SHELL_IN" -lc "$*"
	exit $?
fi

printf '\033[38;5;44m::\033[0m entering %s (exit or ctrl-d to leave)\n' "$TARGET"
env -i \
	HOME=/root \
	TERM="${TERM:-linux}" \
	PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
	ARCTIC_CHROOT=1 \
	chroot "$TARGET" "$SHELL_IN" -l
rc=$?
printf '\033[38;5;44m::\033[0m left %s\n' "$TARGET"
exit $rc
