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

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

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

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") restores a desktop snapshot
    of the TechLit system hosted in BTRFS volume at $(c btrfs-path)
                                        (default: $(c /var/btrfs))

    The lastest local version will be used by default

  NOTE:
    If no versions are available, use $(g tl-comp-pull) to download
    a version, then $(g tl-img-unpack) to unpack it
"
  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

# Disk for installing bootloader
DISK="/dev/$(lsblk -no pkname "$(df "$BTRFS" | tail -n1 | cut -d' ' -f1)")"

say "Syncing snapshot versions"
COMP_DIR="$BTRFS/@srv" "$ROOT/bin/tl-comp-sync" snapshots

# Snapshots directory
SNAP="$BTRFS/@srv/snapshots"
# Patch version of the desktop snapshot to restore -- 0.0.0
VERSION="${2:-"$(COMP_DIR="$BTRFS/@srv" "$ROOT/bin/tl-comp-latest" snapshots)"}"

if ! [ -d "$SNAP/v$VERSION.d" ]; then
  err ""
  err "Snapshot v$(c "$VERSION") is not available locally."
  err "Download and unpack it continue."
  err ""
  exit 1
fi

role="$(sudo jq -r .role "$BTRFS/@srv/secure/config.json" 2>/dev/null || echo "")"
if [ "$role" != "recovery" ]; then
  if [ -r "/tmp/tl-did-restore" ]; then
    err ""
    err "An image was already restored during this boot."
    err "Reboot before restoring again."
    err ""
    exit 1
  fi
fi

say "Writing $(c "/tmp/tl-did-restore") lockfile"
touch "/tmp/tl-did-restore"

say "Replacing @guest subvol with v$VERSION"
{
  if [ -d "$BTRFS/@guest.prev" ]; then
    run sudo btrfs subvol delete "$BTRFS/@guest.prev"
  fi
  if [ -d "$BTRFS/@guest" ]; then
    run sudo mv "$BTRFS/@guest"{,.prev}
  fi
  run sudo btrfs subvol snap "$SNAP/v$VERSION.d/@guest" "$BTRFS/@guest"
}

say "Replacing @root subvol with v$VERSION"
{
  if [ -d "$BTRFS/@root.prev/home/guest" ]; then
    run sudo btrfs subvol delete "$BTRFS/@root.prev/home/guest"
  fi
  if [ -d "$BTRFS/@root.prev" ]; then
    run sudo btrfs subvol delete "$BTRFS/@root.prev"
  fi
  if [ -d "$BTRFS/@root" ]; then
    run sudo mv "$BTRFS/@root"{,.prev}
  fi
  run sudo btrfs subvol snap "$SNAP/v$VERSION.d/@root" "$BTRFS/@root"
}

# Handoff to tl-sys-personalize and tl-hw-update-bootloader
set +e
run sudo "$ROOT/bin/tl-sys-personalize" "$BTRFS" || : # In case a hack fails
run sudo "$ROOT/bin/tl-hw-update-bootloader" "$DISK"
set -e

say "Done."
