#!/usr/bin/env bash
set -Eeuo pipefail

APP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$APP_ROOT"
APP_ENV="${APP_ENV:-staging}"
SITE_URL="${SITE_URL:-https://staging.marlothparkcentral.com}"
EXPECTED_VERSION="$(node -p "require('./package.json').version")"
export NODE_ENV=production
export APP_ENV
export SITE_URL
export NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-$SITE_URL}"
export MPC_PUBLIC_SITE_URL="${MPC_PUBLIC_SITE_URL:-$SITE_URL}"
export MPC_RUNTIME_ROOT="${MPC_RUNTIME_ROOT:-$(cd "$APP_ROOT/.." && pwd)/mpc-runtime-${APP_ENV}}"
export NEXT_TELEMETRY_DISABLED=1

case "$MPC_RUNTIME_ROOT" in
  "$APP_ROOT"|"$APP_ROOT"/*)
    printf 'ERROR: MPC_RUNTIME_ROOT must be outside %s\n' "$APP_ROOT" >&2
    exit 1
    ;;
esac

NODE_MAJOR="$(node -p "process.versions.node.split('.')[0]")"
if [[ "$NODE_MAJOR" != "20" ]]; then
  printf 'ERROR: Activate the cPanel Node 20 environment before deployment. Active runtime: %s\n' "$(node -v)" >&2
  exit 1
fi

if [[ ! -f .htaccess ]] || ! grep -q 'CLOUDLINUX PASSENGER CONFIGURATION BEGIN' .htaccess; then
  printf 'ERROR: cPanel has not generated its Passenger configuration. Save or recreate the Node.js app with startup file server.js, then rerun this script.\n' >&2
  exit 1
fi

mkdir -p \
  "$MPC_RUNTIME_ROOT/state" \
  "$MPC_RUNTIME_ROOT/uploads/admin" \
  "$MPC_RUNTIME_ROOT/uploads/accommodation" \
  "$MPC_RUNTIME_ROOT/uploads/local-listings" \
  "$MPC_RUNTIME_ROOT/uploads/hero-video" \
  "$MPC_RUNTIME_ROOT/thumbnails"
chmod 700 "$MPC_RUNTIME_ROOT" "$MPC_RUNTIME_ROOT/state" "$MPC_RUNTIME_ROOT/uploads" 2>/dev/null || true

printf 'MPC application: %s\n' "$APP_ROOT"
printf 'Persistent runtime: %s\n' "$MPC_RUNTIME_ROOT"
printf 'Node runtime: %s\n' "$(node -v)"

# CloudLinux owns node_modules as a virtual-environment symlink. npm install is
# intentionally used instead of npm ci because npm ci removes node_modules and
# can destroy the selector-managed symlink.
npm install --omit=dev --no-audit --no-fund
node scripts/cpanel-preflight.js
node scripts/cpanel-merge-htaccess.js
node scripts/cpanel-sanitize-runtime.js
npm run build:prebuilt
npm run audit:cpanel-install

mkdir -p tmp
touch tmp/restart.txt
printf 'Passenger restart requested: %s/tmp/restart.txt\n' "$APP_ROOT"
printf 'Verify after Passenger is ready:\n  bash scripts/verify-live-staging.sh %s %s\n' "$SITE_URL" "$EXPECTED_VERSION"
