#!/bin/bash
set -euo pipefail

PKG_DIR="$(cd "$(dirname "$0")" && pwd)"
ACCOUNT_ID=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --account)
      ACCOUNT_ID="${2:-}"
      shift 2
      ;;
    *)
      echo "Unknown argument: $1"
      exit 2
      ;;
  esac
done

ACCOUNTS_DIR="$HOME/.accio/accounts"
if [[ ! -d "$ACCOUNTS_DIR" ]]; then
  echo "Accio Work account directory not found: $ACCOUNTS_DIR"
  exit 1
fi

if [[ -z "$ACCOUNT_ID" ]]; then
  mapfile -t ACCOUNTS < <(find "$ACCOUNTS_DIR" -mindepth 1 -maxdepth 1 -type d -exec basename {} \; | sort)
  if [[ "${#ACCOUNTS[@]}" -eq 1 ]]; then
    ACCOUNT_ID="${ACCOUNTS[0]}"
  else
    echo "Multiple Accio Work accounts found. Pass --account <account_id>."
    printf '%s
' "${ACCOUNTS[@]}"
    exit 1
  fi
fi

TARGET="$ACCOUNTS_DIR/$ACCOUNT_ID"
BACKUP_ROOT="$HOME/.accio/aios-install-backups"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP="$BACKUP_ROOT/$ACCOUNT_ID-before-aios-p0-$STAMP"
mkdir -p "$BACKUP_ROOT"
/usr/bin/ditto "$TARGET" "$BACKUP"

python3 "$PKG_DIR/validate_install.py" --package "$PKG_DIR" --mode local --report "$PKG_DIR/reports/install-macos-local-$STAMP.json"

python3 "$PKG_DIR/validate_install.py" --package "$PKG_DIR" --mode apply --target "$TARGET" --report "$PKG_DIR/reports/install-macos-apply-$STAMP.json"
python3 "$PKG_DIR/validate_install.py" --package "$PKG_DIR" --mode verify --target "$TARGET" --report "$PKG_DIR/reports/install-macos-verify-$STAMP.json"

echo "AIOS AW P0 installed."
echo "Target: $TARGET"
echo "Backup: $BACKUP"
