#!/bin/sh
set -eu

BUNDLE_ZIP=""
INSTALL_DIR="$HOME/Applications/Arrab"
BUNDLE_META_JSON=""
SKIP_HASH_CHECK=0

while [ $# -gt 0 ]; do
  case "$1" in
    --bundle-zip=*) BUNDLE_ZIP=${1#*=} ;;
    --install-dir=*) INSTALL_DIR=${1#*=} ;;
    --bundle-meta-json=*) BUNDLE_META_JSON=${1#*=} ;;
    --skip-hash-check) SKIP_HASH_CHECK=1 ;;
    *) echo "Unknown argument: $1" >&2; exit 1 ;;
  esac
  shift
done

pass=0
fail=0

ok() {
  echo "PASS	$1"
  pass=$((pass + 1))
}

bad() {
  echo "FAIL	$1" >&2
  fail=$((fail + 1))
}

if command -v docker >/dev/null 2>&1; then
  ok "docker command exists"
else
  bad "docker command missing"
fi

if docker info >/dev/null 2>&1; then
  ok "docker engine reachable"
else
  bad "docker engine not reachable (start Docker Desktop)"
fi

if docker compose version >/dev/null 2>&1; then
  ok "docker compose available"
else
  bad "docker compose missing"
fi

if command -v python3 >/dev/null 2>&1; then
  ok "python3 available"
else
  bad "python3 missing"
fi

if [ -n "$BUNDLE_ZIP" ]; then
  if [ ! -f "$BUNDLE_ZIP" ]; then
    bad "bundle missing: $BUNDLE_ZIP"
  else
    ok "bundle exists"
    if [ -z "$BUNDLE_META_JSON" ] && [ -f "$BUNDLE_ZIP.meta.json" ]; then
      BUNDLE_META_JSON="$BUNDLE_ZIP.meta.json"
    fi
    if [ "$SKIP_HASH_CHECK" -eq 0 ] && [ -n "$BUNDLE_META_JSON" ] && [ -f "$BUNDLE_META_JSON" ]; then
      ACTUAL="$(shasum -a 256 "$BUNDLE_ZIP" | awk '{print tolower($1)}')"
      EXPECTED="$(python3 - "$BUNDLE_META_JSON" <<'PY'
import json, sys
with open(sys.argv[1], 'r', encoding='utf-8') as fh:
    data = json.load(fh)
print(str(data.get('zip_sha256', '')).lower())
PY
)"
      if [ -n "$EXPECTED" ] && [ "$ACTUAL" = "$EXPECTED" ]; then
        ok "bundle sha256 matches meta"
      else
        bad "bundle sha256 mismatch"
      fi
    fi
    python3 - "$BUNDLE_ZIP" <<'PY'
import sys, zipfile
with zipfile.ZipFile(sys.argv[1]) as zf:
    names = set(zf.namelist())
    needed = {'arrab-release.json', 'admin/', 'access/', 'includes/'}
    if 'arrab-release.json' not in names:
        raise SystemExit(1)
PY
    if [ $? -eq 0 ]; then
      ok "bundle metadata readable"
    else
      bad "bundle metadata invalid"
    fi
  fi
fi

mkdir -p "$(dirname "$INSTALL_DIR")"
if [ ! -e "$INSTALL_DIR" ]; then
  ok "install dir parent ready"
elif [ -f "$INSTALL_DIR/arrab-release.json" ] || [ -f "$INSTALL_DIR/config_db.php" ]; then
  ok "install dir contains existing Arrab install"
else
  ok "install dir exists"
fi

echo "ARRAB_MAC_PREFLIGHT_DONE	pass=$pass	fail=$fail"
[ "$fail" -eq 0 ]
