#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
MARKER='/etc/learnitive/.deployment'
PROFILE="${LEARNITIVE_DEPLOYMENT_PROFILE:-}"
SITE_ROOT="$(dirname -- "$ROOT_DIR")"
# A release unpacked directly into /var/www/learnitive.com/public_html is
# production by location. This takes precedence over a stale staging marker so
# the operator can simply extract the production ZIP and run ../run.sh.
if [[ -z "$PROFILE" && "$SITE_ROOT" == '/var/www/learnitive.com' ]]; then
  PROFILE='www'
fi
if [[ -z "$PROFILE" && -f "$MARKER" ]]; then
  if grep -Fxq 'domain=www.learnitive.com' "$MARKER" 2>/dev/null; then
    PROFILE='www'
  elif grep -Fxq 'domain=edu.learnitive.com' "$MARKER" 2>/dev/null; then
    PROFILE='staging'
  elif grep -Fxq 'domain=os.learnitive.com' "$MARKER" 2>/dev/null; then
    # Backward compatibility for a pre-edu staging marker. The staging installer
    # will normalize this only when the operator is running from the approved
    # edu.learnitive.com staging tree.
    PROFILE='staging'
  fi
fi
PROFILE="${PROFILE:-staging}"
case "$PROFILE" in
  staging) exec "$ROOT_DIR/deploy/learnitive/install-staging.sh" "$@" ;;
  www) exec "$ROOT_DIR/deploy/learnitive/install-production-www.sh" "$@" ;;
  *) printf '[Learnitive installer] ERROR: unsupported deployment profile %s\n' "$PROFILE" >&2; exit 2 ;;
esac
