#!/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##*/}") creates a new snapshot of the TechLit system
    hosted in BTRFS volume at $(c btrfs-path) (default: $(c /var/btrfs))

    The next patch version will be used by default
      (for example, $(c 0.0.0) becomes $(c 0.0.1))
"
  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 snapshot versions"
"$ROOT/bin/tl-comp-sync" snapshots

# Snapshots directory
SNAP="/srv/snapshots"

# The major version -- x.x.x
PATCH="${2:-"$("$ROOT/bin/tl-comp-latest" snapshots \
  | sed -e 's;\.; ;g' \
  | awk '{print $1"."$2"."($3+1)}')"}"
# The major 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"

assert_parent() {
  local ver="$1"

  if ! [ -d "$SNAP/v$ver.d/@root" ] || ! [ -d "$SNAP/v$ver.d/@guest" ]; then
    err ""
    err "Snapshot v$(c "$ver") is not available locally."
    err ""
    err "Maybe you meant to create it instead?"
    err "  $(g "${BASH_SOURCE##*/}") $(c "$ver")"
    err ""
    exit 1
  fi
}

if [ "$PATCH" != "$MAJOR" ]; then assert_parent "$MAJOR"; fi
if [ "$PATCH" != "$MINOR" ]; then assert_parent "$MINOR"; fi

# TODO: use combined config file
say "Writing system version to $(c /etc/tl-desktop-version)"
{
  run root-write "$BTRFS/@root/etc/tl-desktop-version" "$PATCH"
  run sudo chmod 644 "$BTRFS/@root/etc/tl-desktop-version"
}

say "Running tl-sys-save-guest-session to prepare guest suvbol"
run sudo "$ROOT/bin/tl-sys-save-guest-session" "$BTRFS"

say "Anonymizing system"
run sudo "$ROOT/bin/tl-sys-anonymize" "$BTRFS"

say "Creating new readonly snapshot"
{
  run sudo mkdir -p "$SNAP/v$PATCH.d"

  for subvol in @root @guest; do
    if [ -d "$SNAP/v$PATCH.d/$subvol" ]; then
      run sudo btrfs subvol delete "$SNAP/v$PATCH.d/$subvol"
    fi
    run sudo btrfs subvol snap -r "$BTRFS/$subvol" "$SNAP/v$PATCH.d/$subvol"
  done
}

say "Personalize system"
run sudo "$ROOT/bin/tl-sys-personalize" "$BTRFS"

say "Updating snapshot versions"
"$ROOT/bin/tl-comp-sync" snapshots

say "Done."
