#!/usr/bin/env bash
# Alaysalee Store — Namecheap shared-hosting STAGING preflight. READ-ONLY.
#
#   Upload this one file to your home directory, then in cPanel → Terminal (or SSH):
#     bash ~/preflight-host.sh staging-store.alaysalee.com
#
# It only reads and prints. It never writes to ~/public_html (the live corporate site), never
# changes cron, never connects to the corporate database, and never prints passwords or keys.
# Exit code: 0 = no FAIL lines (WARNs need a human look), 1 = at least one FAIL.
set -uo pipefail
HOST="${1:-}"
APP="${STORE_APP_DIR:-$HOME/store_app}"
WEB="${STORE_WEB_ROOT:-$HOME/store_web_root}"
ENVF="$APP/shared/.env"
fails=0; warns=0
pass() { printf '  PASS  %s\n' "$*"; }
warn() { printf '  WARN  %s\n' "$*"; warns=$((warns+1)); }
fail() { printf '  FAIL  %s\n' "$*"; fails=$((fails+1)); }
ver_ge() { [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -1)" = "$2" ]; }  # $1 >= $2
envval() { [ -r "$ENVF" ] && grep -E "^$1=" "$ENVF" | tail -1 | cut -d= -f2- | sed -e 's/^"//' -e 's/"$//'; }

echo "Alaysalee Store host preflight — $(date -u '+%Y-%m-%d %H:%M UTC') — user $(whoami)"
[ "$(id -u)" = "0" ] && { echo "Do not run as root."; exit 1; }

echo "[1] Isolation from the live corporate site"
PUB="$(cd "$HOME/public_html" 2>/dev/null && pwd -P || echo "$HOME/public_html")"
for d in "$APP" "$WEB"; do
  real="$(cd "$d" 2>/dev/null && pwd -P || echo "$d")"
  case "$real/" in "$PUB/"*) fail "$d is inside public_html — choose a path outside it";; *) pass "$d is outside public_html";; esac
done
[ -d "$HOME/public_html" ] && pass "public_html present (left untouched; this script never writes there)" || warn "no public_html found"

echo "[2] PHP for the store (needs >= 8.4.1)"
PHPB=""
for c in "${PHP_BIN:-}" /opt/cpanel/ea-php84/root/usr/bin/php /opt/alt/php84/usr/bin/php /usr/local/bin/php php; do
  [ -n "$c" ] && command -v "$c" >/dev/null 2>&1 && "$c" -r 'exit(PHP_VERSION_ID >= 80401 ? 0 : 1);' 2>/dev/null && { PHPB="$c"; break; }
done
if [ -z "$PHPB" ]; then fail "no PHP 8.4 CLI found (cPanel → Select PHP Version / MultiPHP: choose 8.4 for the store domain; set PHP_BIN=... if it lives elsewhere)"
else
  pass "PHP CLI $("$PHPB" -r 'echo PHP_VERSION;') at $PHPB"
  for e in pdo_mysql mbstring intl sodium fileinfo gd zip openssl curl ctype tokenizer xml bcmath; do
    "$PHPB" -r 'exit(extension_loaded($argv[1]) ? 0 : 1);' "$e" 2>/dev/null && pass "ext $e" || fail "ext $e missing (Select PHP Version → Extensions)"
  done
  "$PHPB" -r 'echo function_exists("imagewebp") ? "" : "x";' | grep -q x && fail "GD without WebP support (product images are re-encoded to WebP)" || pass "GD WebP encoding available"
  mem="$("$PHPB" -r 'echo ini_get("memory_limit");')"; up="$("$PHPB" -r 'echo ini_get("upload_max_filesize");')"; post="$("$PHPB" -r 'echo ini_get("post_max_size");')"
  echo "        memory_limit=$mem upload_max_filesize=$up post_max_size=$post max_execution_time=$("$PHPB" -r 'echo ini_get("max_execution_time");')"
  case "$mem" in -1|*G|[3-9][0-9][0-9]M|[1-9][0-9][0-9][0-9]M) pass "memory_limit >= 256M";; 256M) pass "memory_limit 256M";; *) warn "memory_limit $mem (256M+ recommended)";; esac
  dis="$("$PHPB" -r 'echo ini_get("disable_functions");')"
  echo "$dis" | grep -qw proc_open && warn "proc_open disabled (fine for the web app; artisan schedule:run still works)" || pass "proc_open available"
fi

echo "[3] Node.js for the Nuxt app (needs >= 20.19)"
NODEB=""
for c in "${NODE_BIN:-}" $(ls -d "$HOME"/nodevenv/*/*/bin/node 2>/dev/null | sort -V | tail -1) node; do
  [ -n "$c" ] && command -v "$c" >/dev/null 2>&1 && { NODEB="$c"; break; }
done
if [ -z "$NODEB" ]; then warn "no node on PATH — create the app in cPanel → Setup Node.js App (Node 22) first, then re-run"
else v="$("$NODEB" -v | tr -d v)"; ver_ge "$v" "20.19.0" && pass "Node $v ($NODEB)" || fail "Node $v is too old (choose 22 in Setup Node.js App)"; fi

echo "[4] Store directories"
for d in "$APP" "$APP/shared" "$APP/shared/storage" "$APP/shared/media" "$APP/private/files" "$APP/backups" "$APP/releases"; do
  [ -d "$d" ] && pass "exists $d" || warn "missing $d (create per docs/DEPLOYMENT_NAMECHEAP.md §2)"
done
for d in "$APP/private/files" "$APP/backups"; do
  [ -d "$d" ] && { m="$(stat -c %a "$d" 2>/dev/null || stat -f %Lp "$d")"; [ "$m" = "700" ] && pass "$d is 700" || fail "$d is $m (must be 700)"; }
done
if [ -f "$ENVF" ]; then m="$(stat -c %a "$ENVF" 2>/dev/null || stat -f %Lp "$ENVF")"; [ "$m" = "600" ] && pass ".env is 600" || fail ".env is $m (chmod 600)"
else warn "no $ENVF yet (copy backend/.env.example there and fill it)"; fi

echo "[5] Store .env sanity (values are never printed)"
if [ -r "$ENVF" ]; then
  [ "$(envval APP_ENV)" = "staging" ] && pass "APP_ENV=staging" || warn "APP_ENV is '$(envval APP_ENV)' (use staging on the staging host)"
  [ "$(envval APP_DEBUG)" = "false" ] && pass "APP_DEBUG=false" || fail "APP_DEBUG must be false"
  [ -n "$(envval APP_KEY)" ] && pass "APP_KEY set" || fail "APP_KEY empty (php artisan key:generate --show, paste it)"
  [ "$(envval PAYMENTS_LIVE_ENABLED)" = "true" ] && fail "PAYMENTS_LIVE_ENABLED=true on staging" || pass "live payments disabled"
  case "$(envval STRIPE_SECRET)" in sk_live_*|rk_live_*) fail "a LIVE Stripe key is configured";; "") pass "no Stripe key yet (checkout stays closed)";; *) pass "Stripe key is test-mode";; esac
  [ "$(envval STORE_REQUIRE_VERIFIED_CLAIMS)" = "false" ] && fail "STORE_REQUIRE_VERIFIED_CLAIMS=false (sample products could be sold)" || pass "verified-claims checkout guard on"
  # V1 launch scope: one-time products only (docs/security/FINANCIAL_SECURITY_AUDIT.md F-07, docs/GO_NO_GO.md).
  case "$(envval STORE_SUBSCRIPTIONS_ENABLED | tr 'A-Z' 'a-z')" in true|1|on|yes) fail "STORE_SUBSCRIPTIONS_ENABLED is on — V1 sells one-time products only";; *) pass "subscriptions disabled (V1 scope)";; esac
  case "$(envval PHYSICAL_COMMERCE_ENABLED | tr 'A-Z' 'a-z')" in true|1|on|yes) fail "PHYSICAL_COMMERCE_ENABLED is on — physical sales are not part of V1";; *) pass "physical sales disabled";; esac
  if [ -n "$(envval STRIPE_SECRET)" ]; then
    case "$(envval STRIPE_WEBHOOK_SECRET)" in whsec_*) pass "Stripe webhook signing secret set (from the Dashboard endpoint for this host)";; *) fail "STRIPE_SECRET set but STRIPE_WEBHOOK_SECRET missing — every webhook would be refused";; esac
    [ -n "$(envval STRIPE_API_VERSION)" ] && pass "STRIPE_API_VERSION pinned" || warn "STRIPE_API_VERSION not pinned"
  fi
  t="$(envval STOREFRONT_PURGE_TOKEN)"; [ ${#t} -ge 32 ] && pass "cache purge token set (${#t} chars)" || warn "STOREFRONT_PURGE_TOKEN unset/short — CMS edits appear within 2 min instead of instantly"
  case "$(envval PRIVATE_FILES_ROOT)" in "$PUB"*) fail "PRIVATE_FILES_ROOT is inside public_html";; "") warn "PRIVATE_FILES_ROOT unset";; *) pass "PRIVATE_FILES_ROOT outside public_html";; esac
  if [ -n "$PHPB" ] && [ -n "$(envval DB_DATABASE)" ]; then
    DBH="$(envval DB_HOST)" DBP="$(envval DB_PORT)" DBN="$(envval DB_DATABASE)" DBU="$(envval DB_USERNAME)" DBW="$(envval DB_PASSWORD)" "$PHPB" -r '
      try { $p = new PDO("mysql:host=".getenv("DBH").";port=".(getenv("DBP") ?: 3306).";dbname=".getenv("DBN"), getenv("DBU"), getenv("DBW"), [PDO::ATTR_TIMEOUT => 5]);
        echo "  PASS  store database reachable: ".$p->query("SELECT VERSION()")->fetchColumn()." (".getenv("DBN").")\n"; }
      catch (Throwable $e) { echo "  FAIL  cannot connect to the store database (".get_class($e).")\n"; exit(1); }' || fails=$((fails+1))
  fi
fi

echo "[6] Disk, inodes, cron, outbound network"
df -h "$HOME" 2>/dev/null | tail -1 | awk '{print "        disk: "$4" free of "$2}'
command -v quota >/dev/null 2>&1 && quota -s 2>/dev/null | tail -2 | sed 's/^/        /'
crontab -l >/dev/null 2>&1 && pass "crontab readable (add the lines from deploy/crontab.txt yourself in cPanel → Cron Jobs)" || warn "no crontab yet (normal before setup)"
if command -v curl >/dev/null 2>&1; then
  sc="$(curl -s -o /dev/null -m 8 -w '%{http_code}' https://api.stripe.com/v1/charges)"
  [ "$sc" != "000" ] && pass "outbound HTTPS to api.stripe.com (HTTP $sc without a key, as expected)" || fail "cannot reach api.stripe.com over HTTPS"
  [ -n "$HOST" ] && { c="$(curl -s -o /dev/null -m 10 -w '%{http_code}' "https://$HOST/")"; [ "$c" != "000" ] && pass "https://$HOST answers ($c) with a valid certificate" || fail "https://$HOST unreachable or TLS invalid (cPanel → SSL/TLS Status → Run AutoSSL)"; }
fi
MH="$(envval MAIL_HOST)"; MP="$(envval MAIL_PORT)"
if [ -n "$MH" ] && [ -n "$PHPB" ]; then
  MH="$MH" MP="${MP:-587}" "$PHPB" -r '$s=@fsockopen(getenv("MH"),(int)getenv("MP"),$e,$m,6); echo $s ? "  PASS  SMTP ".getenv("MH").":".getenv("MP")." reachable\n" : "  FAIL  SMTP ".getenv("MH").":".getenv("MP")." unreachable\n";'
else warn "MAIL_HOST not configured yet"; fi

echo "[7] Can this host run the Nuxt SSR server? (read-only signals; real proof needs the staging deploy)"
command -v cloudlinux-selector >/dev/null 2>&1 && pass "CloudLinux Node.js selector present (cPanel → Setup Node.js App)" || warn "cloudlinux-selector not found — ask Namecheap whether 'Setup Node.js App' is enabled on this plan"
command -v passenger-config >/dev/null 2>&1 && pass "Phusion Passenger present ($(passenger-config --version 2>/dev/null | head -1))" || warn "passenger-config not on PATH (normal on some plans; Setup Node.js App provisions it)"
ls -d "$HOME"/nodevenv/*/ >/dev/null 2>&1 && pass "existing Node.js app environments: $(ls -d "$HOME"/nodevenv/*/ 2>/dev/null | wc -l | tr -d ' ')" || warn "no Node.js app created yet (expected before staging setup)"
echo "        process/memory limits (LVE): processes=$(ulimit -u 2>/dev/null) virtual_mem=$(ulimit -v 2>/dev/null) open_files=$(ulimit -n 2>/dev/null)"
if [ -n "$NODEB" ]; then
  # Starts an in-memory HTTP server on 127.0.0.1 (random port), requests it once, and exits. Writes nothing.
  r="$("$NODEB" -e 'const h=require("http");const s=h.createServer((q,r)=>r.end("ok")).listen(0,"127.0.0.1",()=>{h.get("http://127.0.0.1:"+s.address().port,(r)=>{let b="";r.on("data",d=>b+=d);r.on("end",()=>{console.log(b);s.close()})}).on("error",()=>{console.log("err");s.close()})});setTimeout(()=>{console.log("timeout");process.exit(0)},5000).unref()' 2>&1)"
  [ "$r" = "ok" ] && pass "Node can run a local HTTP server (prerequisite for Nuxt SSR)" || fail "Node could not serve a local HTTP request ($r) — Nuxt SSR will not run here"
fi
warn "Nuxt SSR is NOT proven by this script. Proof = staging: Setup Node.js App → .output/server/index.mjs, then https://<staging>/_ready returns 200 and a product page renders server-side (docs/STAGING_READINESS.md §3)"

echo
echo "Result: $fails FAIL, $warns WARN.  Record the outcome in docs/STAGING_READINESS.md (host checks table)."
[ "$fails" -eq 0 ]
