#!/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##*/}") unpacks desktop a archive into
    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 desktop archives are available, use $(g tl-comp-pull) to download one
"
  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

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

# The patch version -- x.x.x
PATCH="${2:-"$("$ROOT/bin/tl-comp-latest" desktop)"}"
# The minor version -- x.x.0
MINOR="$(echo "$PATCH" | cut -d. -f-2).0"
# The major version -- x.0.0
MAJOR="$(echo "$PATCH" | cut -d. -f-1).0.0"

ARCH="/srv/desktop"             # Archives directory
SNAP="$BTRFS/@srv/snapshots"    # Snapshots directory
TMP="tmp-$(uuidgen | head -c4)" # Temp prefix

#
## Minis: Check for disk size; set up stage; delete old snapshotss
#
DELETE_ARCHIVE_AFTER_UNPACK=false
DISK_SIZE_GB=$(df -B1G "$BTRFS" | tail -n1 | awk '{print $2}')

if [[ "$DISK_SIZE_GB" -lt 20 ]]; then
  say "Setting up the STAGE for minis"
  TMP="mini"
  DEFAULT_STAGE=/srv/stage

  if [ ! -d /srv/stage ] || [ ! -w /srv/stage ]; then
    run sudo rm -rf /srv/stage || :
    run mkdir /srv/stage
  fi

  # Delete @root and @guest subvolumes
  # INFO: We need space to do anything
  run sudo btrfs subvolume delete "$BTRFS"/@root/home/guest "$BTRFS"/@{root,guest} || :
  run sudo rm -rf "$BTRFS"/@root "$BTRFS"/@guest || :

  # Delete all snapshots if not what we want

  find "$SNAP" -mindepth 1 -maxdepth 1 -type d | while read -r dir; do
    keep=false
    dir=$(basename "$dir")

    for ver in "$MAJOR" "$MINOR" "$PATCH"; do
      if [[ "$dir" == v"$ver.d" ]] && [ -d "$SNAP/$dir/@root" ] && [ -d "$SNAP/$dir/@guest" ]; then
        keep=true
        break
      fi
    done

    if ! $keep; then
      sudo btrfs subvolume delete "$SNAP/$dir"/@{root,guest} || true
      if [ -d "$SNAP/$dir" ]; then
        run sudo rm -rf "$SNAP/$dir"
      fi
    fi
  done
elif [[ "$DISK_SIZE_GB" -ge 20 ]] && [[ "$DISK_SIZE_GB" -lt 32 ]]; then
  say "Setting up the STAGE for devices with less than 32G"
  DEFAULT_STAGE=/srv/stage

  if [ ! -d /srv/stage ] || [ ! -w /srv/stage ]; then
    run sudo rm -rf /srv/stage || :
    run mkdir /srv/stage
  fi
else
  DEFAULT_STAGE="$BTRFS/@srv/snapshots"
fi

STAGE="${STAGE:-"$DEFAULT_STAGE"}"

for ver in "$MAJOR" "$MINOR" "$PATCH"; do
  if [ -d "$SNAP/v$ver.d/@root" ] && [ -d "$SNAP/v$ver.d/@guest" ]; then
    continue
  fi

  if ! [ -f "$ARCH/v$ver.tar.gz" ]; then
    err ""
    err "Snapshot v$c$ver$r must be installed, but"
    err "  desktop archive v$c$ver$r is not available locally."
    err ""
    err "Download it with ${g}tl-comp-pull$r to continue."
    err ""
    exit 1
  fi

  run sudo mkdir -p "$SNAP/$TMP.$ver.d"
  if ! [ -f "$STAGE/$TMP.$ver.d/@root.btrfs" ] || ! [ -f "$STAGE/$TMP.$ver.d/@guest.btrfs" ]; then
    say "Verifying checksums"
    if ! (cd "$ARCH" && sha256sum -c "v$ver.sha256"); then
      err ""
      err "Desktop ${c}v$ver$r is corrupt or incmoplete!"
      err "  Could not verify ${c}$ver.sha256$r validity."
      err ""
      err "Download it with ${g}tl-comp-pull$r to try again."
      err ""
      exit 1
    fi

    run sudo mkdir -p "$STAGE/$TMP.$ver.d"
    run sudo tar -C "$STAGE/$TMP.$ver.d" -xzf "$ARCH/v$ver.tar.gz"
  fi

  for subvol in @root @guest; do
    run sudo btrfs receive -f "$STAGE/$TMP.$ver.d/$subvol.btrfs" "$SNAP/$TMP.$ver.d"
    # For devices with less than 20GB, we keep the unpacked snapshots
    if [[ "$DISK_SIZE_GB" -ge 20 ]]; then
      run sudo rm "$STAGE/$TMP.$ver.d/$subvol.btrfs"
    fi
  done

  run mv "$SNAP/$TMP.$ver.d" "$SNAP/v$ver.d"
done

#if [ -n "$STAGE" ]; then
#  say "Balacing BTRFS"
#  run sudo btrfs balance --full-balance "$BTRFS"
#fi

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

say "Done."
