#!/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"
HOSTNAME="${2:-"tli-$(uuidgen | cut -d- -f2)"}"
if [ -z "$DISK" ] || [ -z "$HOSTNAME" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c /dev/sdx)  [$(c hostname)]

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") creates partitions and installs components
    for a TechLit installer USB on $(c /dev/sdx).
  "
  exit 1
fi

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

say "This script will need root access via $(c sudo)"
sudo echo thank you

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

say "Purging USB partition table"
run sudo dd if="/dev/zero" of="$DISK" status=progress bs=1M count=10

say "Creating new partition table"
{
  run sudo parted "$DISK" -s mktable gpt || true
  run sudo parted "$DISK" -s mkpart primary 0 10M || true
  run sudo parted "$DISK" -s mkpart primary fat32 10M 522M || true
  run sudo parted "$DISK" -s mkpart primary 522M 1500M || true
  run sudo parted "$DISK" -s mkpart primary ext4 1500M 100% || true
  run sudo parted "$DISK" -s set 1 bios_grub on || true
  run sudo parted "$DISK" -s set 2 esp on || true
}

say "Waiting for kernel to recognize new partitions"
{
  part_name=$(echo "$DISK"2 | sed -e 's;/dev/;;g')
  while ! sudo lsblk | grep -q "$part_name"; do
    run sudo partprobe "$DISK"
    run sleep 0.5
  done
}

say "Creating filesystems"
{
  run sudo mkfs.fat -F32 "${DISK}2"
  run sudo mke2fs -t ext4 -F "${DISK}4"
}

say "Mounting root filesystem (and un-mounting on errors or exit)"
{
  cleanup() {
    say "Un-mounting root filesystem"
    if sudo grep -q "$PREFIX" "/etc/mtab"; then
      run sudo umount -R "$PREFIX"
    fi
  }

  run sudo mount "${DISK}4" "$PREFIX"
  run sudo rm -df "$PREFIX/lost+found"
}

say "Installing blob components"
for comp in admin desktop recovery; do
  run sudo mkdir -p "$PREFIX/$comp"
  run "$ROOT/bin/tl-comp-sync" "$comp"
done

say "Installing $(c secure)"
{
  run sudo mkdir -p "$PREFIX/secure"

  run sudo chmod 700 "$PREFIX/secure"
  run sudo mkdir -p -m 700 "$PREFIX/secure/ssh"
  run sudo mkdir -p -m 700 "$PREFIX/secure/net/system-connections"
  run sudo mkdir -p -m 700 "$PREFIX/secure/net/lib"
  run sudo touch "$PREFIX/secure/known_hosts"
  run sudo touch "$PREFIX/secure/bash_history"
}

# say "Creating SSH identity"
# {
#   dir="$PREFIX/secure/ssh"
#   for algo in ecdsa ed25519 rsa; do
#     key="$dir/ssh_host_${algo}_key"
#     if [ -f "$key" ]; then
#       say " >> Destroying existing keys: $(c "$key{,.pub}")"
#       run sudo rm "$key"{,.pub}
#     fi
#     run sudo ssh-keygen -f "$key" -N "" -t "$algo" -C "admin@$HOSTNAME"
#   done
# }

say "Creating persistent system config"
run root-write "$PREFIX/secure/config.json" "$(jq -n '{
  role: "installer",
  hostname: "$HOSTNAME",
}')"

say "Changing ownership"
run sudo chown -R "$ADMIN_UID:$ADMIN_GID" "$PREFIX"

# Handoff to tl-usb-update-{recovery,components}
cleanup
cleanup() { :; }
run "$ROOT/bin/tl-usb-update-recovery" "$DISK"
run "$ROOT/bin/tl-usb-update-components" "$DISK"
