#!/usr/bin/env bash
# vim:et:ts=2:sts=2:sw=2

# Get absolute repository root (especially when symlinked)
ROOT="$(realpath "$(dirname "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")")")"

# Load accompanying bash library
source "$ROOT/lib/lib.bash"

DISK="$1"
USER="${2:-"admin"}"
PREFIX="${PREFIX:-"$(mktemp -d)"}"

# Exit now unless run as root
assert-is-root

if [ -z "$DISK" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c /dev/sdx)  [$(c user)]

	DESCRIPTION:
	$(g "${BASH_SOURCE##*/}") mounts partitions and chroots into
	a TechLit system on $(c /dev/sdx)
	"
fi

set-partitions "$DISK"

say "Mounting system (and un-mounting on errors or exit)"
{
  cleanup() {
    say "Un-mounting system"
    tl-chroot-unmount
    run umount -qR "$PREFIX"
  }

  run mount "$ROOT_PART" -o subvol="@root" "$PREFIX"
  run mount "$ROOT_PART" -o subvol="@srv" "$PREFIX/srv"
  run mount "$ROOT_PART" "$PREFIX"/var/btrfs
  run mount "$EFI_PART" "$PREFIX/boot/efi"
  tl-chroot-mount
}

chroot "$PREFIX" /bin/bash && umount -qR "$PREFIX"
