#!/usr/bin/env bash
#
# ArchitectOS upgrade helper (Unix skeleton)
#
# Usage:
#   aos-upgrade /path/to/architectos-X.Y.Z.tar.gz
#
set -euo pipefail

if [[ $# -lt 1 ]]; then
  echo "Usage: $0 /path/to/architectos-X.Y.Z.tar.gz" >&2
  exit 1
fi

TARBALL="$1"

if [[ ! -f "$TARBALL" ]]; then
  echo "[upgrade] Tarball not found: $TARBALL" >&2
  exit 1
fi

if [[ -z "${AOS_INSTALL_ROOT:-}" ]]; then
  echo "[upgrade] AOS_INSTALL_ROOT is not set. This command is intended to be run via the installed 'aos-upgrade' wrapper." >&2
  exit 1
fi

INSTALL_ROOT="$AOS_INSTALL_ROOT"
VENV_PATH="${INSTALL_ROOT}/venv"
CURRENT_LINK="${INSTALL_ROOT}/current"

BASENAME="$(basename "$TARBALL")"
if [[ "$BASENAME" =~ architectos-([0-9.]+)\.tar\.gz ]]; then
  VERSION="${BASENAME#architectos-}"
  VERSION="${VERSION%.tar.gz}"
else
  echo "[upgrade] WARNING: Could not parse version from tarball name. Using 'dev'." >&2
  VERSION="dev"
fi

VERSION_DIR="${INSTALL_ROOT}/${VERSION}"

echo "[upgrade] Install root: $INSTALL_ROOT"
echo "[upgrade] Tarball: $TARBALL"
echo "[upgrade] Target version: $VERSION"
echo "[upgrade] Version dir: $VERSION_DIR"
echo "[upgrade] Venv: $VENV_PATH"

mkdir -p "$VERSION_DIR"

echo "[upgrade] Extracting tarball..."
tar xzf "$TARBALL" -C "$VERSION_DIR" --strip-components=1

if [[ ! -d "$VENV_PATH" ]]; then
  echo "[upgrade] Creating virtualenv..."
  python3 -m venv "$VENV_PATH"
fi

echo "[upgrade] Installing Python dependencies for new version..."
if [[ -f "$VERSION_DIR/requirements.txt" ]]; then
  "$VENV_PATH/bin/pip" install --upgrade pip
  "$VENV_PATH/bin/pip" install -r "$VERSION_DIR/requirements.txt"
else:
  echo "[upgrade] WARNING: requirements.txt not found in new version."
fi

echo "[upgrade] Updating 'current' symlink..."
ln -sfn "$VERSION_DIR" "$CURRENT_LINK"

echo "[upgrade] Done. Now using ArchitectOS version: $VERSION"
