#!/bin/sh
set -eu

BUNDLE_ZIP=""
INSTALL_DIR="$HOME/Applications/Arrab"
COMPANY_NAME="Arrab"
ADMIN_USER="admin"
ADMIN_PASSWORD="Arrab123!"
DB_NAME="arrab"
DB_USER="root"
DB_PASSWORD="arrab"
DB_HOST="db"
DB_PORT=""
LANG_CODE="ar_EG"
HTTP_PORT="8080"
WEB_IMAGE="arrab-macos-web"
SKIP_HASH_CHECK=0
BUNDLE_META_JSON=""

while [ $# -gt 0 ]; do
  case "$1" in
    --bundle-zip=*) BUNDLE_ZIP=${1#*=} ;;
    --install-dir=*) INSTALL_DIR=${1#*=} ;;
    --company-name=*) COMPANY_NAME=${1#*=} ;;
    --admin-user=*) ADMIN_USER=${1#*=} ;;
    --admin-password=*) ADMIN_PASSWORD=${1#*=} ;;
    --db-name=*) DB_NAME=${1#*=} ;;
    --db-user=*) DB_USER=${1#*=} ;;
    --db-password=*) DB_PASSWORD=${1#*=} ;;
    --db-host=*) DB_HOST=${1#*=} ;;
    --db-port=*) DB_PORT=${1#*=} ;;
    --lang=*) LANG_CODE=${1#*=} ;;
    --http-port=*) HTTP_PORT=${1#*=} ;;
    --web-image=*) WEB_IMAGE=${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

if [ -z "$BUNDLE_ZIP" ] || [ ! -f "$BUNDLE_ZIP" ]; then
  echo "Bundle missing: $BUNDLE_ZIP" >&2
  exit 1
fi

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname "$0")" && pwd)"
PREFLIGHT_ARGS="--bundle-zip=$BUNDLE_ZIP --install-dir=$INSTALL_DIR"
if [ -n "$BUNDLE_META_JSON" ]; then
  PREFLIGHT_ARGS="$PREFLIGHT_ARGS --bundle-meta-json=$BUNDLE_META_JSON"
fi
if [ "$SKIP_HASH_CHECK" -eq 1 ]; then
  PREFLIGHT_ARGS="$PREFLIGHT_ARGS --skip-hash-check"
fi
# shellcheck disable=SC2086
sh "$SCRIPT_DIR/preflight-arrab.sh" $PREFLIGHT_ARGS

rm -rf "$INSTALL_DIR"
mkdir -p "$INSTALL_DIR"
python3 - "$BUNDLE_ZIP" "$INSTALL_DIR" <<'PY'
import sys, zipfile
bundle, out = sys.argv[1], sys.argv[2]
with zipfile.ZipFile(bundle) as zf:
    zf.extractall(out)
print("UNZIP_OK", out)
PY

cd "$INSTALL_DIR"
printf 'ARRAB_HTTP_PORT=%s\nARRAB_WEB_IMAGE=%s\n' "$HTTP_PORT" "$WEB_IMAGE" > .env
DOCKER_BUILDKIT=0 docker build -t "$WEB_IMAGE" .
docker compose up -d --no-build

for _ in $(seq 1 40); do
  if docker compose ps db 2>/dev/null | grep -q "healthy"; then
    break
  fi
  sleep 2
done

docker compose exec -T web php scripts/arrab_install_headless.php \
  "--db-host=$DB_HOST" \
  "--db-port=$DB_PORT" \
  "--db-name=$DB_NAME" \
  "--db-user=$DB_USER" \
  "--db-password=$DB_PASSWORD" \
  "--company-name=$COMPANY_NAME" \
  "--admin-user=$ADMIN_USER" \
  "--admin-password=$ADMIN_PASSWORD" \
  "--lang=$LANG_CODE"

LAUNCHER="$INSTALL_DIR/Open Arrab.command"
cat > "$LAUNCHER" <<'EOF'
#!/bin/sh
PORT_FILE="$(CDPATH= cd -- "$(dirname "$0")" && pwd)/.env"
PORT="$(awk -F= '/^ARRAB_HTTP_PORT=/{print $2}' "$PORT_FILE" 2>/dev/null)"
[ -n "$PORT" ] || PORT="8080"
open "http://127.0.0.1:${PORT}"
EOF
chmod +x "$LAUNCHER"

python3 - "$INSTALL_DIR/bootstrap-install-receipt.json" "$INSTALL_DIR" "$BUNDLE_ZIP" "$DB_NAME" "$ADMIN_USER" "$HTTP_PORT" <<'PY'
import json, sys, datetime
receipt = {
    "installed_at": datetime.datetime.now().isoformat(timespec="seconds"),
    "install_dir": sys.argv[2],
    "bundle_zip": sys.argv[3],
    "app_url": f"http://127.0.0.1:{sys.argv[6]}",
    "db_name": sys.argv[4],
    "admin_user": sys.argv[5],
    "platform": "macOS",
}
with open(sys.argv[1], "w", encoding="utf-8") as fh:
    json.dump(receipt, fh, ensure_ascii=False, indent=2)
print("RECEIPT_OK", sys.argv[1])
PY

open "http://127.0.0.1:${HTTP_PORT}"
echo "ARRAB_MAC_INSTALL_OK	$INSTALL_DIR	http://127.0.0.1:${HTTP_PORT}"
