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

USB="$1"
VERSION="$2"
BTRFS="${3:-"/var/btrfs"}" # Path to system BTRFS root

if [ -z "$USB" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
  $(g "${BASH_SOURCE##*/}") [$(c USB)] [$(c btrfs-path)]

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") Updates a TechLit system
    hosted in BTRFS volume at $(c btrfs-path) (default: $(c /var/btrfs))
    Using the update files from USB
  "
  exit 1
fi

# Exit now unless run as admin
assert-is-user

PREFIX="$(mktemp -d)"

if ! mountpoint -q "$USB"; then
  say "Mounting USB..."
  cleanup() {
    sudo umount -q "$PREFIX"
  }
  run sudo mount "$USB"4 "$PREFIX"
fi

SNAP="$BTRFS"/@srv/snapshots

say "Syncing versions..."
PATCH="${VERSION:-$(COMP_DIR="$PREFIX" tl-comp-latest desktop)}"
MINOR="$(echo "$PATCH" | cut -d. -f-2).0"
MAJOR="$(echo "$PATCH" | cut -d. -f-1).0.0"
ADMIN="$(COMP_DIR="$PREFIX" tl-comp-latest admin)"

say "Copying update files..."
rsync -avP "$PREFIX"/admin/v"$ADMIN".* /srv/admin || :

for version in "$MAJOR" "$MINOR" "$PATCH"; do
  if [ -d "$SNAP/v$version.d"/@root ] && [ -d "$SNAP/v$version.d"/@guest ]; then
    continue
  else
    run rsync -avP "$PREFIX"/desktop/v"$version".* /srv/desktop
  fi
done
run sudo umount -q "$PREFIX"
say "$(c It is safe to unmount the USB now...)"

run "$ROOT"/bin/tl-archive-install admin

say "Handing off to tl-img-*..."
{
  run "$ROOT/bin/tl-img-unpack" "$BTRFS"
  run "$ROOT/bin/tl-img-restore" "$BTRFS"
}

if read -r -p "Reboot now? [y/N] " -n 1 && [[ $REPLY =~ ^[Yy]$ ]]; then
  say "Rebooting in 5 seconds... Press Ctrl+C to cancel."
  for i in {5..1}; do
    echo "$i..."
    sleep 1
  done
  sudo reboot
fi

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