#!/usr/bin/env bash

# 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"

# Exit now if run as root user
assert-is-root

ROOT_DEV="$3" # Path to root block device
VOL_DEV="$2" # Path to volume block device
if [ -z "$ROOT_DEV" ] || [ -z "$VOL_DEV" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c /dev/root-dev)  $(c /dev/srv-vol)

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") installs and configures bootloaders for the
    TechLit Artix mirror installed on $(c /dev/root-dev).
  "
  exit 1
fi

# Mountpoint to use
PREFIX="${PREFIX:-"$(mktemp -d)"}"

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_DEV}2" "$PREFIX"
  run mount "${VOL_DEV}1" "$PREFIX/srv"
  tl-chroot-mount
}

say "Installing fstab and rc.conf from host state"; {
  SRC="$PREFIX/srv/secure" DEST="$PREFIX"
  run tl-install "fstab" 0 0 644 "/etc/fstab"
  run tl-install "rc.conf" 0 0 644 "/etc/rc.conf"
}

if ! [ -d "$PREFIX/grub/i386-pc" ]; then
  say "Installing grub MBR bootloaders for i386"
  run root-chroot "grub-install --target=i386-pc '$ROOT_DEV'"
fi

say "Configuring bootloaders"; {
  root_uuid=$(lsblk "${ROOT_DEV}1" -no UUID)

  run write "$PREFIX/boot/grub/grub.cfg" "
default=0
timeout=0

menuentry 'TechLit Mirror' {
  search --no-floppy --fs-uuid --set=root $root_uuid

  linux /boot/vmlinuz \
    root=UUID=$root_uuid init=/sbin/init tl-role=mirror \
    net.ifnames=0 vconsole.unicode=1 vconsole.keymap=us locale.LANG=en_US.UTF-8 \
    ro rd.luks=0 rd.dm=0 add_efi_memmap

  initrd /boot/initrd
}
"
}

# Unmount system and quiet exit hook
cleanup; cleanup() { :; }
say "Done."
