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

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

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

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") clones the system archive with the version given
    ($(c version)) into already-provisioned desktop system on $(c /dev/sdx).

    The lastest local version will be used by default.

  NOTE:
    Run $(g tl-hw-prepare) on $(c /dev/sdx) first to prepare the disk and
    clone required components before installing the filesystem update.
  "
  exit 1
fi

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

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

# Set the root partition
set-partitions "$DISK"

# Exit if disk is mounted
if mount | grep -q "$DISK"; then
  err "$(r "$DISK") is mounted, aborting..."
  say "If sure it's not the USB drive, unmount it and try again"
  exit 1
fi

say "Mounting system (and un-mounting on errors or exit)"
{
  cleanup() {
    say "Un-mounting system"
    run sudo umount -qR "$PREFIX"
  }
  run sudo mount "$ROOT_PART" "$PREFIX"
}

run "$ROOT/bin/tl-img-unpack" "$PREFIX" "$VERSION"
run "$ROOT/bin/tl-img-restore" "$PREFIX" "$VERSION"

# Handoff to grub installer
# shellcheck disable=SC2218
cleanup
cleanup() { :; }
say "Done."
