#!/usr/bin/env bash
# cPanel servers only. Keeps cPanel in step with the platform: every site
# address the platform knows about gets a cPanel subdomain (or alias for a
# client's own verified domain), an Apache rule that sends it to the platform,
# and an AutoSSL certificate. install.sh runs this every 2 minutes from cron,
# so a client site you add in the admin console goes live on its own.
#
#   bash scripts/cpanel-sync.sh            # sync now
#   bash scripts/cpanel-sync.sh --remove   # take the platform off Apache (your old site shows again)
set -euo pipefail
cd "$(dirname "$0")/.."
[ -f .cpanel-user ] || { echo "not a cPanel install"; exit 0; }
set -a; source .env; set +a

ROOT="$PLATFORM_DOMAIN"
CPUSER="$(cat .cpanel-user)"
UD="${APACHE_USERDATA:-/etc/apache2/conf.d/userdata}"
CP_SCRIPTS="${CPANEL_SCRIPTS:-/scripts}"
CP_BIN="${CPANEL_BIN:-/usr/local/cpanel/bin}"
LOCK="${SYNC_LOCK:-/var/run/meatbrand-cpanel-sync.lock}"
CONF=meatbrand-proxy.conf
STATE=.cpanel-synced
touch "$STATE"

exec 9>"$LOCK"
flock -n 9 || exit 0

rebuild_apache() {
  "$CP_SCRIPTS/rebuildhttpdconf" >/dev/null
  "$CP_SCRIPTS/restartsrv_httpd" --graceful >/dev/null 2>&1 || "$CP_SCRIPTS/restartsrv_httpd" >/dev/null
}

if [ "${1:-}" = "--remove" ]; then
  find "$UD" -path "*/$CPUSER/*" -name "$CONF" -delete 2>/dev/null || true
  rm -f "$STATE"
  rebuild_apache
  echo "Platform proxy rules removed. The cPanel account's normal website folder is served again."
  echo "(Re-enable with: bash scripts/cpanel-sync.sh)"
  exit 0
fi

HOSTS="$(curl -fsS --max-time 10 http://127.0.0.1:4100/internal/hosts)" || { echo "$(date) platform API not reachable; skipping"; exit 0; }

changed=0
need_ssl=0

render_std() { cat <<'EOF'
# Managed by The Meat Brand (scripts/cpanel-sync.sh). Do not edit.
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/\.well-known/
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
EOF
}

render_ssl() { cat <<'EOF'
# Managed by The Meat Brand (scripts/cpanel-sync.sh). Do not edit.
<IfModule proxy_http_module>
  ProxyRequests Off
  ProxyPreserveHost On
  RequestHeader set X-Forwarded-Proto "https"
  RequestHeader set X-Via-Edge "1"
  <Location "/api/internal">
    Require all denied
  </Location>
  ProxyPass /.well-known/ !
  ProxyPass /api/internal !
  ProxyPass /api/ http://127.0.0.1:4100/ timeout=60
  ProxyPassReverse /api/ http://127.0.0.1:4100/
  ProxyPass / http://127.0.0.1:3100/ timeout=60
  ProxyPassReverse / http://127.0.0.1:3100/
</IfModule>
EOF
}

write_include() { # $1 = vhost name as cPanel stores it (domain or full subdomain)
  local t d f want
  for t in std ssl; do
    d="$UD/$t/2_4/$CPUSER/$1"; f="$d/$CONF"
    want="$(render_$t)"
    if [ ! -f "$f" ] || [ "$(cat "$f")" != "$want" ]; then
      mkdir -p "$d"; printf '%s\n' "$want" > "$f"; changed=1
    fi
  done
}

domain_exists() { uapi --user="$CPUSER" DomainInfo single_domain_data domain="$1" 2>/dev/null | grep -q '^ *status: 1'; }

ensure_sub() { # $1 = label under ROOT
  local fq="$1.$ROOT"
  if ! grep -qx "sub $fq" "$STATE"; then
    if ! domain_exists "$fq"; then
      if uapi --user="$CPUSER" SubDomain addsubdomain domain="$1" rootdomain="$ROOT" dir="public_html/meatbrand-sites" disallowdot=1 \
          | grep -q '^ *status: 1'; then
        echo "$(date) added subdomain $fq"
      else
        echo "$(date) WARNING: could not add subdomain $fq in cPanel"; return 0
      fi
    fi
    echo "sub $fq" >> "$STATE"; need_ssl=1
  fi
  write_include "$fq"
}

ensure_alias() { # $1 = client's own verified domain; shares the main domain's Apache config
  if ! grep -qx "alias $1" "$STATE"; then
    if ! domain_exists "$1"; then
      if uapi --user="$CPUSER" Park park domain="$1" | grep -q '^ *status: 1'; then
        echo "$(date) added alias domain $1"
      else
        echo "$(date) WARNING: could not add alias $1 in cPanel (check WHM > Tweak Settings > 'Allow remote domains')"; return 0
      fi
    fi
    echo "alias $1" >> "$STATE"; need_ssl=1; changed=1
  fi
}

# The main domain (www is already an alias of it in cPanel)
write_include "$ROOT"

while read -r kind host; do
  [ -n "${kind:-}" ] || continue
  case "$kind" in
    platform)
      if [ "$host" != "$ROOT" ] && [ "$host" != "www.$ROOT" ]; then ensure_sub "${host%.$ROOT}"; fi ;;
    sub) ensure_sub "$host" ;;
    custom) ensure_alias "$host" ;;
  esac
done <<< "$HOSTS"

if [ "$changed" = 1 ]; then rebuild_apache; echo "$(date) Apache updated"; fi
if [ "$need_ssl" = 1 ]; then
  nohup "$CP_BIN/autossl_check" --user="$CPUSER" >/dev/null 2>&1 &
  echo "$(date) AutoSSL requested for $CPUSER"
fi
