#!/bin/bash
# Idempotent: push local dev code -> production CMS (194.x.x.x).
#
#   bash /home/fix-cms-production.sh
#
# Env: /home/env/production.env (prod) | development.env (local, no deploy)

set -euo pipefail

# shellcheck source=/home/env/load-env.sh
source /home/env/load-env.sh "${XTREAM_ENV:-production}"
require_production_deploy

CMS_ROOT="${CMS_ROOT:-/home/xtreamcodes/iptv_xtream_codes}"
LOCAL_ROOT="${LOCAL_ROOT:-/home/xtreamcodes/iptv_xtream_codes}"
MAIN_ROOT="${MAIN_ROOT:-/home/xtreamcodes/iptv_xtream_codes}"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=15"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "$SCRIPT_DIR/lib/cms-panel-bootstrap.sh" ]; then
  # shellcheck source=lib/cms-panel-bootstrap.sh
  source "$SCRIPT_DIR/lib/cms-panel-bootstrap.sh"
elif [ -f /home/lib/cms-panel-bootstrap.sh ]; then
  # shellcheck source=/home/lib/cms-panel-bootstrap.sh
  source /home/lib/cms-panel-bootstrap.sh
else
  echo "ERROR: lib/cms-panel-bootstrap.sh not found" >&2
  exit 1
fi

echo "[*] fix-cms-production [$XTREAM_ENV] -> $CMS_HOST (local code -> prod)"

sshpass -p "$CMS_PASS" ssh $SSH_OPTS "root@$CMS_HOST" \
  "DEBIAN_FRONTEND=noninteractive apt-get update -qq
   DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nginx openssl rsync curl sshpass mariadb-client libmcrypt4 python3-paramiko 2>/dev/null || true"

if [ -d "$LOCAL_ROOT/admin" ]; then
  echo "[*] Rsync local admin/pytools/crons -> prod CMS"
  for sub in admin pytools crons; do
    sshpass -p "$CMS_PASS" rsync -az --delete -e "ssh $SSH_OPTS" \
      "$LOCAL_ROOT/$sub/" "root@${CMS_HOST}:${CMS_ROOT}/$sub/"
  done
  sshpass -p "$CMS_PASS" rsync -az -e "ssh $SSH_OPTS" \
    "$LOCAL_ROOT/lib/curl/" "root@${CMS_HOST}:${CMS_ROOT}/lib/curl/"
  sshpass -p "$CMS_PASS" rsync -az -e "ssh $SSH_OPTS" \
    "$LOCAL_ROOT/php/bin/php.real" "root@${CMS_HOST}:${CMS_ROOT}/php/bin/"
  echo "[*] Rsync LB/CACHE/MAIN edge fixes -> CMS mirror source"
  sshpass -p "$CMS_PASS" rsync -az -e "ssh $SSH_OPTS" \
    "$LOCAL_ROOT/wwwdir/play_live.php" \
    "$LOCAL_ROOT/wwwdir/play_hls.php" \
    "root@${CMS_HOST}:${CMS_ROOT}/wwwdir/"
  sshpass -p "$CMS_PASS" rsync -az -e "ssh $SSH_OPTS" \
    "$LOCAL_ROOT/wwwdir/streaming/cache_auth.php" \
    "$LOCAL_ROOT/wwwdir/streaming/adaptive_live_prep.php" \
    "root@${CMS_HOST}:${CMS_ROOT}/wwwdir/streaming/"
  sshpass -p "$CMS_PASS" rsync -az -e "ssh $SSH_OPTS" \
    "$LOCAL_ROOT/nginx/conf/nginx.conf.xc" \
    "$LOCAL_ROOT/nginx/conf/adaptive_rewrite_first.conf" \
    "$LOCAL_ROOT/nginx/conf/nginx.conf.cache.template" \
    "$LOCAL_ROOT/nginx/conf/nginx.conf.cache.ready" \
    "$LOCAL_ROOT/nginx/conf/cache_edge_active.conf" \
    "$LOCAL_ROOT/nginx/conf/cache_edge_locations.conf" \
    "$LOCAL_ROOT/nginx/conf/cache_edge_auth.conf" \
    "$LOCAL_ROOT/nginx/conf/cache_panel_auth_upstream.conf" \
    "$LOCAL_ROOT/nginx/conf/cache_edge_proxy_headers.conf" \
    "$LOCAL_ROOT/nginx/conf/cache_edge_cors.conf" \
    "$LOCAL_ROOT/nginx/conf/cache_edge_cors_preflight.conf" \
    "$LOCAL_ROOT/nginx/conf/main_cache_auth_backend.conf" \
    "root@${CMS_HOST}:${CMS_ROOT}/nginx/conf/"
fi

set +e
cms_panel_bootstrap "$CMS_HOST" "$CMS_PASS" "$CMS_VLAN" "$MAIN_HOST" \
  "$MAIN_SSH_HOST" "$MAIN_SSH_PASS" "$CMS_ROOT" "$MAIN_ROOT"
set -e

echo "[*] Full mirror pack -> CMS $CMS_HOST:8080/Files (main/cms/LB/CACHE) ..."
PACK_LB_FROM_GOLDEN="${PACK_LB_FROM_GOLDEN:-0}" \
  LB_HOST="${LB_HOST:-192.168.1.150}" LB_PASS="${LB_PASS:-}" \
  CMS_HOST="$CMS_HOST" CMS_PASS="$CMS_PASS" \
  bash /home/pack-mirror.sh

CMS_PASS="$CMS_PASS" CMS_HOST="$CMS_HOST" SYNC_ONLY=1 bash /home/setup-cms-files.sh

CMS_PASS="$CMS_PASS" CMS_HOST="$CMS_HOST" CMS_VLAN="$CMS_VLAN" \
  MAIN_SSH_HOST="$MAIN_SSH_HOST" MAIN_SSH_PASS="$MAIN_SSH_PASS" \
  MAIN_VLAN="$MAIN_HOST" bash /home/link-cms-main.sh

sshpass -p "$CMS_PASS" ssh $SSH_OPTS "root@$CMS_HOST" \
  "grep -q xtream-files /etc/nginx/sites-enabled/* 2>/dev/null || cat > /etc/nginx/sites-available/xtream-files.conf <<'NGX'
server {
    listen 8080 default_server;
    listen [::]:8080 default_server;
    server_name _;
    root /var/www/html;
    server_tokens off;
    autoindex on;
    location /Files/ {
        alias /var/www/html/Files/;
        autoindex on;
        add_header Cache-Control \"public, max-age=60\";
    }
    location = /Files { return 301 /Files/; }
}
NGX
ln -sf /etc/nginx/sites-available/xtream-files.conf /etc/nginx/sites-enabled/xtream-files.conf 2>/dev/null || true
nginx -t && systemctl reload nginx
chown -R xtreamcodes:xtreamcodes /home/xtreamcodes
chmod 600 $CMS_ROOT/config 2>/dev/null || true"

echo "[ok] prod CMS ready — panel http://${CMS_HOST}/ | mirror http://${CMS_HOST}:8080/Files/"
echo "    Full reload LB rotates xt_lb_{id} password (prepareLbDatabaseCredentials rotate=true)"
