#!/bin/bash
# panel-migrate-site <domain> [old-db-container] [cpanel-account]   (databases are named <cpanel-account>_...)
# Move one site from a copied cPanel account (in /root/migrate) onto this server:
# docroot + databases it uses + SSL certificate + vhost + its cron jobs (as the site user, not root).
# Databases that already exist here with tables are NOT overwritten (they may be live already).
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
d="${1:?domain}"; c="${2:-old80}"; M=/root/migrate; u="$PANEL_USER"; acct="${3:-$u}"
f=$(grep -l "^servername: $d\.\|^servername: $d$" $M/userdata/* 2>/dev/null | grep -vE "_SSL|cache" | head -1)
[ -n "$f" ] || die "no cPanel userdata for $d"
root=$(awk '/^documentroot:/{print $2}' "$f")
[ -d "$root" ] || die "docroot missing: $root"
echo "== $d  ($root)"
# databases: every <account>_* name in the site's PHP config files that is a real database on the old server
olddbs=$(podman exec "$c" mysql -uroot -N -e "select schema_name from information_schema.schemata")
for db in $(grep -rhoE --include=*.php "${acct}_[A-Za-z0-9_]+" "$root" --exclude-dir=vendor --exclude-dir=node_modules --exclude-dir='_backup*' 2>/dev/null | sort -u); do
  grep -qx "$db" <<< "$olddbs" || continue
  n=$(mysql -N -e "select count(*) from information_schema.tables where table_schema='$db'")
  if [ "$n" -gt 0 ]; then echo "   db $db: already here ($n tables) — kept"; else panel-migrate-db "$c" "$db" | sed 's/^/   db /'; fi
done
# ssl
sslname=$(ls $M/ssl | grep -E "^$d\.|^$d$" | head -1 || true)
if [ -n "$sslname" ] && [ -s "$M/ssl/$sslname/combined" ]; then panel-ssl-import-cpanel "$d" "$M/ssl/$sslname/combined" | grep notAfter | sed 's/^/   ssl /'; else echo "   ssl: none on old server (Let's Encrypt after DNS switch)"; fi
panel-site-add "$d" "$root" "$u" | sed 's/^/   /'
# crons from the old root crontab (run.sh lines) → user crontab with panel-cron-run (keeps # disabled lines disabled)
cur=$(crontab -u $u -l 2>/dev/null || true)
if ! grep -q "^# --- $d ---" <<< "$cur"; then
  add=$(grep -E "run\.sh +$d " $M/cron/root | sed -E "s#/root/cron/run\.sh#/usr/local/bin/panel-cron-run#; s#[[:space:]]+\#.*##" || true)
  if [ -n "$add" ]; then printf '%s\n# --- %s ---\n%s\n' "$cur" "$d" "$add" | sed '/^$/d' | crontab -u $u -; echo "   crons: $(grep -vc '^#' <<< "$add") active, $(grep -c '^#' <<< "$add") disabled"; else echo "   crons: none"; fi
fi
# quick local test
code=$(curl -s -o /dev/null -w "%{http_code} %{time_total}s" --resolve "$d:443:127.0.0.1" --resolve "$d:80:127.0.0.1" "$( [ -s $PANEL_SSL/$d/fullchain.pem ] && echo https || echo http )://$d/")
echo "   test: $code"
