#!/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 unless run as root user
assert-is-root

PREFIX="$1" # System root prefix
VERSION="$2" # Version of this ISO (x.x.x)
if [ -z "$PREFIX" ] || [ -z "$VERSION" ] || [ -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 /tmp/rootfs)

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") bootstraps a new TechLit artix ISO
    in the $(c /tmp/rootfs) directory from scratch using either
    the upstream artix repos or a local cache.

    The version given ($(c 0.0.0)) will be written to the ISO.

  NOTE:
    You probably don't want to run this script yourself. It should be run
    via $(c tl-bake-recovery) and $(c mkarchiso) instead.
  "
  exit 1
fi

# Always use the default hostname
HOSTNAME="tli-000"

# Directories to purge before baking
PURGE=("var/cache" "run" "var/run")

# Roles to install
ROLES=(global hardware recovery)

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

  bash-completion
  tmux vim htop
  git curl rsync jq tar

  binutils xz xorriso
  device-mapper dracut-network openresolv dhclient

  grub-i386-efi
  grub-x86_64-efi
  parted efibootmgr

  NetworkManager bind-utils openntpd runit-nftables
  openssh

  nss-mdns avahi-utils

  acpi b43-firmware
)

say "Mounting system (and un-mounting on errors or exit)"; {
  cleanup() {
    say "Un-mounting system"
    tl-chroot-unmount
  }
  tl-chroot-mount
}

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

say "Configuring users"; {
  # Adding admin
  run root-chroot "groupadd -f -g $ADMIN_GID $ADMIN_GROUP"
  run root-chroot "useradd -g $ADMIN_GID -u $ADMIN_UID $ADMIN_USER"
  run root-chroot "groupadd -f network"
  run root-chroot "usermod -a -G wheel,network $ADMIN_USER"

  # Locking accounts
  run root-chroot "passwd -dl root"
  pass="$(echo "$ADMIN_PASS" | openssl passwd -1 -stdin)"
  run root-chroot "echo '$ADMIN_USER:$pass' | chpasswd -e"
}

say "Writing system version to $(c /etc/tl-recovery-version)"
run root-write "$PREFIX/etc/tl-recovery-version" "$VERSION"
run sudo chmod 644 "$PREFIX/etc/tl-recovery-version"

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

say "Removing runtime files"
for tree in "${PURGE[@]}"; do
  run rm -rf "$PREFIX/$tree/"*
done

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