#!/usr/bin/env bash
#
# Deploy an ALREADY BUILT company website to a web-root directory:
#
#   npx ng build website --base-href /website/
#   projects/website/deploy/deploy.sh /home/moonui/public_html/website moonui
#
# It does not build: /fullpush builds every app first (a failing build blocks the
# merge and every deploy), and this script only installs that artefact.
#
#   1. `assets/config.json` is gitignored and never emitted by the build (only
#      `config.json.example`). The target's own file is kept; a target without one
#      gets `projects/website/src/assets/config.json` (gitignored, per install), else
#      the deploy FAILS — a site without its config shows the config-error screen.
#      moonui: {"apiUrl":"https://moonui.elbaset.com/moon-erp-be/api/website",
#               "defaultLang":"ar","routerBase":"/website/"}
#   2. `.htaccess` is installed from the repo on EVERY deploy — a stale one survives
#      the clean-up forever (storefront 2026-07-22 lesson).
#   3. The root SEO discovery bridge (robots.txt / sitemaps) is refreshed in the
#      parent's .htaccess — a website-only install needs it as much as the store.
#
# The script fails loudly rather than deploying something that cannot boot.

set -euo pipefail

TARGET="${1:?usage: deploy.sh <target-dir> [owner]}"
OWNER="${2:-}"
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
DIST="$REPO_ROOT/dist/website/browser"
SRC_CONFIG="$REPO_ROOT/projects/website/src/assets/config.json"
SRC_HTACCESS="$REPO_ROOT/projects/website/public/.htaccess"
ROOT_HTACCESS="$(dirname "$TARGET")/.htaccess"

[ -d "$TARGET" ] || { echo "FATAL: target '$TARGET' does not exist"; exit 1; }

# --- 1. The build must exist (and carry the /website/ base) BEFORE any rm ----
[ -f "$DIST/index.html" ] || {
  echo "FATAL: $DIST/index.html is missing — run: npx ng build website --base-href /website/"
  exit 1
}
grep -q '<base href="/website/"' "$DIST/index.html" || {
  echo "FATAL: built index.html does not carry <base href=\"/website/\"> (D9: one build, /website/ base)."
  exit 1
}
[ -f "$SRC_HTACCESS" ] || { echo "FATAL: $SRC_HTACCESS is missing"; exit 1; }

# --- 2. The runtime config must exist ---------------------------------------
if [ ! -f "$TARGET/assets/config.json" ] && [ ! -f "$SRC_CONFIG" ]; then
  echo "FATAL: no runtime config found."
  echo "  Neither $TARGET/assets/config.json"
  echo "  nor    $SRC_CONFIG"
  echo "Copy assets/config.json.example to one of them and set apiUrl + routerBase first."
  exit 1
fi

# --- 3. Replace build artefacts, preserving assets/config.json --------------
echo "==> deploying to $TARGET"
rm -f "$TARGET"/*.js "$TARGET"/*.css "$TARGET"/*.html "$TARGET"/*.ico
\cp -rf "$DIST"/* "$TARGET"/

if [ ! -f "$TARGET/assets/config.json" ]; then
  echo "==> target had no config.json; installing from src"
  \cp -f "$SRC_CONFIG" "$TARGET/assets/config.json"
fi

# --- 4. Routing / renderer policy, always from the repo ---------------------
echo "==> installing .htaccess policy"
\cp -f "$SRC_HTACCESS" "$TARGET/.htaccess"

echo "==> installing root SEO discovery bridge"
bash "$REPO_ROOT/projects/storefront/deploy/install-root-seo-bridge.sh" "$ROOT_HTACCESS" "$OWNER"

if [ -n "$OWNER" ]; then
  chown -R "$OWNER:$OWNER" "$TARGET"
fi

# --- 5. Prove the deployed site can actually boot ---------------------------
echo "==> verifying"
python3 - "$TARGET/assets/config.json" <<'PY'
import json, sys
cfg = json.load(open(sys.argv[1]))
api, base = cfg.get('apiUrl', ''), cfg.get('routerBase', '')
print(f"    apiUrl        : {api}")
print(f"    routerBase    : {base}")
if not api.rstrip('/').endswith('/api/website'):
    sys.exit('FATAL: apiUrl must end with /api/website')
if not (base.startswith('/') and base.endswith('/')):
    sys.exit('FATAL: routerBase must start and end with "/"')
PY
echo "    base href     : $(grep -o '<base href="[^"]*"' "$TARGET/index.html")"
grep -q '/moon-erp-be/website-seo' "$TARGET/.htaccess" || {
  echo "FATAL: website SEO renderer rewrite is missing from .htaccess"
  exit 1
}
echo
echo "Deployed. Confirm the apiUrl above belongs to THIS instance."
