#!/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 unless run as the admin user
assert-is-admin

SUBJECT="${1:-all}" # Subject to install (eg docs, sheets, rasters or "all")
VERSION="$2"        # Version for the subject

if [[ "${1:-}" =~ ^(-h|--help)$ ]]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  [$(c subject)]  [$(c version)]

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") installs a curriculum subject (or all subjects) into the Desktop

    If $(c subject) is omitted or 'all', all available local subjects will be installed.
    The lastest local version will be used by default for each subject if $(c version) is omitted.

  EXAMPLES:
    $(g "${BASH_SOURCE##*/}")  $(c docs)
    $(g "${BASH_SOURCE##*/}")  $(c shell)  $(c 0.1.20)
    $(g "${BASH_SOURCE##*/}")  $(c all) (default)
"
  exit 1
fi

# Exit now if unless run as the admin user
assert-is-admin

say "This script requires root privileges"
sudo echo "Thank you"

DEST="${DEST:-/var/btrfs/@guest/Desktop}"
TEMP_BASE_DIR="$(mktemp -d)"

cleanup() { sudo rm -rf "$TEMP_BASE_DIR"; }
trap cleanup EXIT

# Track results for summary
SUCCESS_LIST=()
FAILED_LIST=()

install_subject() {
  local subject_name="$1"
  local subject_version="${2:-$("$ROOT"/bin/tl-comp-latest "curriculum" "$subject_name" 2>/dev/null)}"
  local silent="${3:-false}"

  if [ -z "$subject_version" ]; then
    say "$(r WARNING) No local version found for subject $(c "$subject_name"). Skipping installation"
    return 0
  fi

  local SUBJECT_DOWNLOAD_DIR="/srv/curriculum/$subject_name"
  local ARCHIVE_PATH="$SUBJECT_DOWNLOAD_DIR/v$subject_version.tar.gz"

  if [ ! -f "$ARCHIVE_PATH" ]; then
    err "Curriculum archive not found for $(c "$subject_name") v$(c "$subject_version") at $(c "$ARCHIVE_PATH")"
    return 1
  fi

  local SUBJECT_TEMP_DIR="$(mktemp -d -p "$TEMP_BASE_DIR")"
  say "Unpacking $(c "$subject_name") v$(c "$subject_version") into $SUBJECT_TEMP_DIR"
  run tar -xzf "$ARCHIVE_PATH" -C "$SUBJECT_TEMP_DIR"

  # Detect build type
  local DEST_PATH="$DEST/$subject_name"
  if [ -f "$SUBJECT_TEMP_DIR/.full-build" ] || [ ! -d "$DEST_PATH" ]; then
    say "Full installation: replacing existing $(c "$subject_name") in $DEST_PATH"
    run sudo rm -rf "$DEST_PATH" || true
    run sudo mkdir -p "$DEST_PATH"
  else
    say "Patch installation: merging updates into $(c "$subject_name") in $DEST_PATH"
    # Handle deletions (.deleted)
    if [ -f "$SUBJECT_TEMP_DIR/.deleted" ]; then
      while read -r file_to_delete; do
        [ -z "$file_to_delete" ] && continue
        if [ -e "$DEST_PATH/$file_to_delete" ]; then
          run sudo rm -rf "$DEST_PATH/$file_to_delete"
        fi
      done <"$SUBJECT_TEMP_DIR/.deleted"
    fi
  fi

  # Merge new/modified files
  run sudo rsync -az "$SUBJECT_TEMP_DIR/" "$DEST_PATH/"

  run sudo chown -R guest:guest "$DEST_PATH"

  # Update local version tracker
  echo "$subject_version" >"/srv/curriculum/$subject_name/.override"

  if ! "$silent"; then
    say "Done. Curriculum $(c "$subject_name") v$(c "$subject_version") is installed at $(c "$DEST_PATH")"
  fi
  return 0
}

if [ "$SUBJECT" = "all" ]; then
  say "Installing all available curriculum subjects."
  # Scan for subjects
  for sub_dir in /srv/curriculum/*; do
    if [ -d "$sub_dir" ] && [ -f "$sub_dir/.v/local" ]; then
      subject_name=$(basename "$sub_dir")
      if install_subject "$subject_name" "$VERSION" true; then
        SUCCESS_LIST+=("$subject_name")
      else
        FAILED_LIST+=("$subject_name")
      fi
    fi
  done
else
  if install_subject "$SUBJECT" "$VERSION"; then
    SUCCESS_LIST+=("$SUBJECT")
  else
    FAILED_LIST+=("$SUBJECT")
  fi
fi

# Final Summary
say ""
if [ ${#SUCCESS_LIST[@]} -gt 0 ]; then
  say "$(g SUCCESS:) Installed subjects: ${SUCCESS_LIST[*]}"
fi
if [ ${#FAILED_LIST[@]} -gt 0 ]; then
  say "$(r FAILED:)  Failed subjects:    ${FAILED_LIST[*]}"
fi

say "All requested curriculum installations complete."
