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

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)"
SITE_ROOT="$(dirname -- "$ROOT_DIR")"
EXPECTED_SITE_ROOT='/var/www/learnitive.com'
EXPECTED_ROOT_LAUNCHER_CONTRACT='www-vhost-cutover-v10'
VHOST_HELPER="$ROOT_DIR/deploy/learnitive/install-www-vhosts.sh"
SUCCESS_MARKER='/etc/learnitive/.successful-release'
STAGING_ROOT='/var/www/edu.learnitive.com'
LEGACY_OS_STAGING_ROOT='/var/www/os.learnitive.com'
SERVICES=(
  learnitive.service
  learnitive-secret-helper.service
  learnitive-console-gateway.service
  learnitive-console-egress.service
  learnitive-egress-proxy.service
  learnitive-universal-runner.service
  learnitive-redis.service
)

log() { printf '[Learnitive production] %s\n' "$*"; }
fail() { printf '[Learnitive production] ERROR: %s\n' "$*" >&2; exit 1; }

[[ "$SITE_ROOT" == "$EXPECTED_SITE_ROOT" ]] || fail "production wrapper must run from $EXPECTED_SITE_ROOT/public_html (found $ROOT_DIR)."
if [[ "${LEARNITIVE_WWW_ROOT_LAUNCHER_CONTRACT:-}" != "$EXPECTED_ROOT_LAUNCHER_CONTRACT" ]]; then
  printf '[Learnitive installer] ERROR: production www must be launched by the current /var/www/learnitive.com/run.sh. The root launcher is missing or stale, so the guarded Apache cutover cannot be trusted. Re-extract the complete release including root run.sh, then run ./run.sh again.\n' >&2
  exit 2
fi
[[ -f "$VHOST_HELPER" ]] || fail "Missing guarded production vhost helper: $VHOST_HELPER"
chmod 0755 "$VHOST_HELPER" "$ROOT_DIR/scripts/verify-www-local-vhost.sh"

normalize_production_config_paths() {
  [[ -d /etc/learnitive ]] || return 0
  local file legacy_root changed=0
  for legacy_root in "$STAGING_ROOT" "$LEGACY_OS_STAGING_ROOT"; do
    while IFS= read -r -d '' file; do
      sed -i "s|$legacy_root|$SITE_ROOT|g" "$file"
      changed=1
    done < <(grep -RIlZF "$legacy_root" /etc/learnitive 2>/dev/null || true)
  done
  if (( changed == 1 )); then
    log 'Normalized remaining Learnitive host configuration paths to the production root.'
  fi
  for legacy_root in "$STAGING_ROOT" "$LEGACY_OS_STAGING_ROOT"; do
    grep -RqsF "$legacy_root" /etc/learnitive 2>/dev/null && fail "/etc/learnitive still contains legacy Learnitive root $legacy_root."
  done

  local unit
  for unit in "${SERVICES[@]}"; do
    for legacy_root in "$STAGING_ROOT" "$LEGACY_OS_STAGING_ROOT"; do
      systemctl cat "$unit" 2>/dev/null | grep -Fq "$legacy_root" && fail "$unit still references legacy Learnitive root $legacy_root."
    done
  done

  # A clean validation deliberately has no grep matches. The final grep in the
  # loop therefore returns 1; without an explicit success return that status
  # escapes this function and `set -e` silently terminates the wrapper before
  # install-www-vhosts.sh --activate can run.
  return 0
}

clear_www_success_marker() {
  if [[ -f "$SUCCESS_MARKER" ]] && grep -Fxq 'domain=www.learnitive.com' "$SUCCESS_MARKER" 2>/dev/null; then
    rm -f -- "$SUCCESS_MARKER"
  fi
}

export LEARNITIVE_DEPLOYMENT_PROFILE=www

# The core application installer intentionally remains ingress-agnostic. Run it
# as a child rather than exec'ing it so this production wrapper itself owns the
# mandatory post-acceptance Apache commit. This makes the site cutover complete
# before control can return to (or be lost from) the root launcher.
if ! "$ROOT_DIR/deploy/learnitive/install-staging.sh" "$@"; then
  fail 'Core production application/runtime acceptance failed before Apache cutover.'
fi
normalize_production_config_paths
log 'Production config path normalization passed; proceeding to the mandatory guarded Apache cutover.'

log 'Installing and verifying www.learnitive.com, apex redirect, and edu.learnitive.com -> www cutover vhosts.'
if ! "$VHOST_HELPER" --activate; then
  clear_www_success_marker
  fail 'Application activation succeeded, but production Apache cutover failed and was rolled back. The www successful-release marker was cleared; fix the reported vhost/TLS issue and rerun ./run.sh.'
fi

log 'Guarded production Apache cutover committed: www.learnitive.com is active; learnitive.com and edu.learnitive.com redirect one hop to www.'
