#!/bin/bash
# Deploy Xtream MAIN on remote server (MariaDB + streaming; panel on CMS).
#
# Usage:
#   MAIN_HOST=194.76.0.147 MAIN_PASS=123852 MAIN_VLAN=17.17.17.101 \
#   MIRROR_URL=http://194.76.0.209:8080/Files \
#   CMS_HOST=194.76.0.209 CMS_VLAN=17.17.17.100 \
#   bash /home/install-main-remote.sh

set -euo pipefail

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

MAIN_HOST="${MAIN_PUBLIC:-194.76.0.147}"
MAIN_PASS="${MAIN_PASS:-}"
MAIN_VLAN="${MAIN_VLAN:-17.17.17.101}"
MIRROR_URL="${MIRROR_URL:-http://${CMS_HOST}:8080/Files}"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=20"
XC="/home/xtreamcodes/iptv_xtream_codes"

if [ -z "$MAIN_PASS" ]; then
  echo "ERROR: MAIN_PASS missing in /home/env/production.env" >&2
  exit 1
fi

echo "[*] MAIN install [$XTREAM_ENV] -> $MAIN_HOST (vlan $MAIN_VLAN)"

ssh_cmd() {
  sshpass -p "$MAIN_PASS" ssh $SSH_OPTS "root@$MAIN_HOST" "$@"
}

echo "[*] MAIN install -> $MAIN_HOST (mirror $MIRROR_URL)"

echo "[*] Preflight"
ssh_cmd "curl -fsS -o /dev/null -w 'mirror main %{http_code}\n' '${MIRROR_URL}/main.tar.gz'"
ssh_cmd "curl -fsS -o /dev/null -w 'database.sql %{http_code}\n' '${MIRROR_URL}/database.sql'"
ssh_cmd "test ! -f $XC/config || { echo 'ERROR: xtream already installed'; exit 1; }"

echo "[*] Packages + install.py + tarballs"
ssh_cmd "export XTREAM_FILES_URL='${MIRROR_URL}' XTREAM_FILES_PORT=8080 DEBIAN_FRONTEND=noninteractive
curl -fsSL '${MIRROR_URL}/install.py' -o /tmp/install.py
curl -fsSL '${MIRROR_URL}/database.sql' -o /tmp/database.sql
curl -fsSL '${MIRROR_URL}/settings_seed.sql' -o /tmp/settings_seed.sql 2>/dev/null || true
curl -fsSL '${MIRROR_URL}/finish_main_install.py' -o /tmp/finish_main_install.py
printf 'MAIN\nY\n\nY\n' | python3 /tmp/install.py 2>&1 | tee /tmp/xtream-main-install.log || true"

echo "[*] Finish DB bootstrap if install.py stalled"
ssh_cmd "test -f $XC/config || MAIN_VLAN='${MAIN_VLAN}' python3 /tmp/finish_main_install.py"

echo "[*] Configure + services"
ssh_cmd "export XTREAM_FILES_URL='${MIRROR_URL}'
curl -fsSL '${MIRROR_URL}/install.py' -o /tmp/install.py
python3 -c \"
import sys; sys.path.insert(0,'/tmp'); import install as i
if not __import__('os').path.isfile(i.XTREAM_BASE+'/config'): raise SystemExit('no config')
i.configure('MAIN'); i.configure_redis('MAIN')
i.run('python3 %s/pytools/strip_main_panel_nginx.py 2>/dev/null || true' % i.XTREAM_BASE)
i.start_services(); i.post_deploy_sync('MAIN')
\""

if [ -n "$MAIN_VLAN" ]; then
  ssh_cmd "mysql -u root -e \"USE xtream_iptvpro; UPDATE streaming_servers SET vpn_ip='${MAIN_VLAN}', server_ip='${MAIN_HOST}' WHERE id=1;\" 2>/dev/null || true"
fi

echo "[*] CMS DB firewall — vlan only ($CMS_VLAN)"
ssh_cmd "echo '${CMS_VLAN}' > $XC/.cms_panel_host
python3 -c \"import json; open('/tmp/fw.json','w').write(json.dumps({'enabled':1,'port':7999,'allow':['127.0.0.1','::1','${CMS_VLAN}']}))\"
python3 $XC/pytools/sync_main_db_firewall.py /tmp/fw.json"

echo "[*] DB credentials"
ssh_cmd "export LD_LIBRARY_PATH=$XC/lib/curl/lib:$XC/lib
$XC/php/bin/php -r \"
chdir('$XC/admin');
define('CONFIG_CRYPT_KEY','5709650b0d7806074842c6de575025b1');
function x(\\\$d,\\\$k){\\\$o='';for(\\\$i=0;\\\$i<strlen(\\\$d);\\\$i++)\\\$o.=chr(ord(\\\$d[\\\$i])^ord(\\\$k[\\\$i%strlen(\\\$k)]));return \\\$o;}
\\\$i=json_decode(x(base64_decode(file_get_contents('$XC/config')),CONFIG_CRYPT_KEY),true);
echo 'db_host='.(\\\$i['host']??'?').':'.(\\\$i['db_port']??'?').\"\\n\";
echo 'db_user='.(\\\$i['db_user']??'?').\"\\n\";
echo 'db_pass='.(\\\$i['db_pass']??'?').\"\\n\";
\""

echo "[ok] MAIN $MAIN_HOST | vlan=$MAIN_VLAN"
echo "    Link CMS: bash /home/link-cms-main.sh CMS_PASS=... MAIN_SSH_PASS=..."
