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

# Path to USB disk
DISK="$1"
if [ -z "$DISK" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c /dev/sdx)

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") updates all components installed on
    the USB at $(c /dev/sdx).

    The latest versions of rsync components will added.

  NOTE:
    You may need to make space on the USB to install the latest components. You can set
    $(c FORCE=absolutely) to erase existing component versions.

    Run $(g tl-usb-prepare) and $(g tl-usb-update-recovery) on $(c /dev/sdx) first
    to prepare the disk and add a bootable ISO first.
  "
  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 "Mounting system and changing ownership"
{
  cleanup() {
    say "Changing ownership & un-mounting system"
    run sudo chown -R "$ADMIN_UID:$ADMIN_GID" "$PREFIX"
    run sudo umount -qR "$PREFIX"
  }
  run sudo mount "${DISK}4" "$PREFIX"
  run sudo rm -df "$PREFIX/lost+found"
  run sudo chown -R "0:0" "$PREFIX"
}

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

[ "$FORCE" = "absolutely" ] && sudo rm -f "$PREFIX/desktop/"*
[ "$FORCE" = "absolutely" ] && sudo rm -f "$PREFIX/recovery/"*

say "Installing latest components"
{
  for comp in admin desktop desktop-mini type; do

    [ ! -d "/srv/$comp" ] || continue
    say "Syncing $comp"
    latest="$("$ROOT/bin/tl-comp-latest" "$comp")"

    if [[ "$comp" =~ ^desktop ]]; then
      minor="$(echo "$latest" | cut -d. -f-2).0"
      major="$(echo "$latest" | cut -d. -f-1).0.0"
      for ver in $major $minor $latest; do
        if ! [ -f "/srv/$comp/v$ver.tar.gz" ] && ! [ -f "$PREFIX/$comp/v$ver.tar.gz" ]; then
          err "$comp v$ver not found. Proceeding anyway..."
        fi
        run sudo rsync --cc=xxh3 -ahvzP --partial --append-verify "/srv/$comp/v$ver"* "$PREFIX/$comp" || :
      done
    fi

    run sudo rsync --cc=xxh3 -ahvzP --partial --append-verify "/srv/$comp/v$latest"* "$PREFIX/$comp" || :
    run sudo SKIP_USER_CHECK=1 COMP_DIR="$PREFIX" "$ROOT"/bin/tl-comp-sync "$comp"
  done
}

desktop_comp="desktop"
is-mini "$DISK" && desktop_comp="desktop-mini"

desktop="$(sudo tail -n1 "$PREFIX/$desktop_comp/.v/local" 2>/dev/null || echo "None")"
admin="$(sudo tail -n1 "$PREFIX/admin/.v/local" 2>/dev/null || echo "None")"

# Cleanup and exit
# shellcheck disable=SC2218
cleanup
cleanup() { :; }

say "\n Components updated:
\t  Desktop: $(g "$desktop") ($desktop_comp)
\t  Admin: $(g "$admin")"
