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

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 "
  $(r TODO:)
    $(r "This command needs to be ported from Void to Artix")

  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c /dev/root-dev)

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") bootstraps a new TechLit artix mirror
    on $(c /dev/root-dev) from scratch using either the upstream artix repos
    or a local cache.

  NOTE:
    Run $(g tl-provision-mirror) on $(c /dev/root-dev) first to prepare the
    partition layout and required repo components before bootstrapping.
  "
  exit 1
fi

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

# Always use the default hostname
HOSTNAME="void.techlitafrica.org"

# Roles to install
ROLES=(global mirror)

# XBPS packages to install
PKGS=(
  base-system void-repo-nonfree
  socklog-void

  bash-completion
  tmux vim htop
  git curl rsync jq tar

  grub-utils
  binutils xz xorriso

  dhcpcd bind-utils openntpd runit-nftables
  lighttpd openssh
)

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
}

# Install & configure system packages
tl-bootstrap-xbps "${PKGS[@]}"

say "Configuring users"; {
  # Removing void
  run root-chroot "userdel -rf void || true"

  # Adding admin
  run root-chroot "groupadd -f -g $ADMIN_GID $ADMIN_GROUP"
  run root-chroot "useradd -u $ADMIN_UID -g $ADMIN_GID $ADMIN_USER"

  # Adding dev
  run root-chroot "groupadd -f -g $DEV_GID $DEV_GROUP"
  run root-chroot "useradd -u $DEV_GID -g $DEV_GID $DEV_USER"
  run root-chroot "usermod -a -G wheel $DEV_USER"

  # Locking accounts
  run root-chroot "passwd -dl root"
  run root-chroot "passwd -dl $DEV_USER"
  run root-chroot "passwd -dl $ADMIN_USER"
}

# Installing TechLit roles
tl-bootstrap-roles "${ROLES[@]}"

# Prepare for bootloader
tl-bootstrap-kernel

# Handoff to grub installer
cleanup; cleanup() { :; }
run "$ROOT/bin/tl-cloud-update-bootloader"
