#!/bin/bash
# Copy MAIN /var/www/html/Files mirror to CMS and serve it on :8080 (nginx).
# Run on MAIN after pack-mirror, or standalone to refresh CMS mirror.
#
# Usage (on MAIN 155):
#   sudo CMS_HOST=194.76.0.209 CMS_PASS=xxx bash /home/setup-cms-files.sh
#   sudo CMS_HOST=192.168.1.158 CMS_PASS=xxx SYNC_ONLY=1 bash /home/setup-cms-files.sh

set -euo pipefail

# shellcheck source=/home/env/load-env.sh
source /home/env/load-env.sh "${XTREAM_ENV:-production}"
if [ "${XTREAM_ENV:-production}" = "development" ]; then
  require_cluster_deploy
else
  require_production_deploy
fi

FILES_SRC="${FILES_SRC:-/var/www/html/Files}"
CMS_FILES="${CMS_FILES:-/var/www/html/Files}"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=15"

echo "[*] Mirror sync [$XTREAM_ENV] -> CMS $CMS_HOST:8080/Files"
if [ ! -d "$FILES_SRC" ]; then
  echo "ERROR: $FILES_SRC missing — run pack-mirror.sh first" >&2
  exit 1
fi

ssh_cmd() {
  sshpass -p "$CMS_PASS" ssh $SSH_OPTS "root@$CMS_HOST" "$@"
}

echo "[*] CMS Files mirror -> $CMS_HOST ($CMS_FILES)"

echo "[*] Rsync Files from MAIN..."
sshpass -p "$CMS_PASS" rsync -az --delete \
  -e "ssh $SSH_OPTS" \
  "$FILES_SRC/" "root@${CMS_HOST}:${CMS_FILES}/"

if [ "${SYNC_ONLY:-0}" = "1" ]; then
  echo "[ok] sync only — skipped nginx setup"
else
  echo "[*] CMS: nginx :8080 for Files mirror"
  ssh_cmd "mkdir -p /var/www/html/Files
chown -R www-data:www-data /var/www/html
chmod -R a+rX /var/www/html/Files
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nginx 2>/dev/null || true
cat > /etc/nginx/sites-available/xtream-files.conf <<'NGX'
# Xtream install mirror — tarballs + install.py (panel LB/CACHE/Main install)
server {
    listen 8080 default_server;
    listen [::]:8080 default_server;
    server_name _;
    root /var/www/html;
    index index.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
nginx -t
systemctl enable nginx
systemctl reload nginx"
fi

echo "[*] CMS: refresh installed edge sources from Files tarballs (avoid stale Sync push)"
ssh_cmd "BASE=/home/xtreamcodes/iptv_xtream_codes
FILES=/var/www/html/Files
for pair in \
  'CACHE.tar.gz iptv_xtream_codes/nginx/conf/cache_edge_active.conf nginx/conf/cache_edge_active.conf' \
  'CACHE.tar.gz iptv_xtream_codes/nginx/conf/cache_edge_proxy_ts_headers.conf nginx/conf/cache_edge_proxy_ts_headers.conf' \
  'CACHE.tar.gz iptv_xtream_codes/nginx/conf/cache_edge_lb_ts_static.conf nginx/conf/cache_edge_lb_ts_static.conf' \
  'main.tar.gz iptv_xtream_codes/wwwdir/streaming/adaptive_lib.php wwwdir/streaming/adaptive_lib.php'; do
  set -- \$pair
  tar=\$1 member=\$2 dest=\$3
  [ -f \"\$FILES/\$tar\" ] || continue
  tar -xOf \"\$FILES/\$tar\" \"\$member\" > \"\$BASE/\$dest.new\" 2>/dev/null || continue
  [ -s \"\$BASE/\$dest.new\" ] || continue
  mv \"\$BASE/\$dest.new\" \"\$BASE/\$dest\"
  echo \"    refreshed \$dest from \$tar\"
done"

if [ "${SYNC_ONLY:-0}" = "1" ]; then
  exit 0
fi

echo "[*] CMS: XTREAM_FILES_URL for panel + crons"
ssh_cmd "mkdir -p /etc/systemd/system/xtream-php-fpm.service.d
cat > /etc/systemd/system/xtream-php-fpm.service.d/files-url.conf <<ENV
[Service]
Environment=XTREAM_FILES_URL=http://${CMS_HOST}:8080/Files
Environment=XTREAM_FILES_PORT=8080
ENV
cat > /etc/profile.d/xtream-files-url.sh <<PROF
export XTREAM_FILES_URL=http://${CMS_HOST}:8080/Files
export XTREAM_FILES_PORT=8080
PROF
chmod 644 /etc/profile.d/xtream-files-url.sh
{ echo 'XTREAM_FILES_URL=http://${CMS_HOST}:8080/Files'
  echo 'XTREAM_FILES_PORT=8080'
  crontab -u xtreamcodes -l 2>/dev/null | grep -v '^XTREAM_FILES' || true
} | crontab -u xtreamcodes -
systemctl daemon-reload"

echo "[*] Verify mirror on CMS"
ssh_cmd "curl -fsSI http://127.0.0.1:8080/Files/install.py | head -3
ls -lh ${CMS_FILES}/main.tar.gz ${CMS_FILES}/cms.tar.gz ${CMS_FILES}/LB.tar.gz ${CMS_FILES}/install.py 2>/dev/null | awk '{print \$5, \$9}'"

echo ""
echo "[ok] CMS Files mirror: http://${CMS_HOST}:8080/Files/"
echo "    install.py / main.tar.gz / LB.tar.gz / CACHE.tar.gz / cms.tar.gz"
echo "    Panel on CMS uses local mirror (XTREAM_FILES_URL) for LB/CACHE install"
