#!/bin/bash
# panel-move-site — move a site to another connected server: files, databases, MySQL users, SSL, cron jobs and DNS.
#   panel-move-site plan   <domain> <server> [--json]    what would move, size, expected pause, warnings (changes nothing)
#   panel-move-site start  <domain> <server> [--no-dns]  start the move in the background (log: /var/log/panel/move-<domain>.log)
#   panel-move-site run    <domain> <server> [--no-dns]  the same in the foreground
#   panel-move-site status [<domain>] [--json]           moves started from this server
#   panel-move-site back   <domain>                      move it back here (asks the other server to move it)
#   panel-move-site finish <domain>                      once DNS has switched everywhere (give it a day): archive the old
#                                                        copy here (files + database dumps in ~/moved/) and stop forwarding
# How a move works: files and databases are copied while the site stays online; then the site pauses for the final
# copy (seconds to a minute, depends on database size), the new server takes over and this one forwards every visitor
# there until DNS has switched everywhere. Cron jobs move with the site, so they never run on two servers.
#   panel-move-site on <server> plan|start|status|finish|back|log …   the same for a site on a connected server
# internal (called on the receiving server): _accept <domain> <docroot> <user> · _cron <user> <docroot>
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
LOGNAME_PANEL=move
MOVES=/var/lib/panel/moves; install -d -m 700 "$MOVES"
EXTRA=/etc/panel/vhost-extra; install -d -m 755 "$EXTRA"
SYSDB='^(information_schema|mysql|performance_schema|sys)$'
STEPS=8

# ---------- facts about the site ----------
gather() {   # sets: d srv rip u root base size dbs dbbytes users cron ssl warn block
  d="$1"; srv="$2"
  valid_domain "$d" || die "invalid domain: $d"
  [ -f "$(site_conf "$d")" ] || die "no site $d on this server"
  rip=$(node_ip "$srv") || die "unknown server: $srv (connect it first: panel-server add)"
  u=$(site_user "$d"); root=$(site_docroot "$d"); base="/home/$u/public_html"
  [ -n "$u" ] && [ -d "$root" ] || die "cannot read the settings of $d"
  [ "$(realpath "$root")" != "$(realpath "$base")" ] || die "$d is served from the main folder $base, which holds the other sites too — it can't be moved on its own"
  case "$root" in "$base"/*) ;; *) die "folder $root is outside $base";; esac
  [[ "$root" =~ ^[A-Za-z0-9/._-]+$ ]] || die "unusual characters in folder name: $root"
  warn=(); block=()
  size=$(du -sb "$root" 2>/dev/null | cut -f1)
  # databases named anywhere in the site's code or config
  local all; all=$(mysql -N -e 'show databases' | grep -Ev "$SYSDB" || true); dbs=()
  if [ -n "$all" ]; then
    mapfile -t dbs < <(grep -rhowF -f <(echo "$all") "$root" --include='*.php' --include='*.inc' --include='*.ini' --include='.env' \
       --include='*.env' --include='*.json' --include='*.yml' --include='*.yaml' --include='*.cnf' --include='*.py' 2>/dev/null | sort -u)
  fi
  # a name that only ever appears on "user" lines is a MySQL login name, not a database this site uses
  local db keep=() inc=(--include='*.php' --include='*.inc' --include='*.ini' --include='.env' --include='*.env' --include='*.json' --include='*.yml' --include='*.yaml' --include='*.cnf' --include='*.py')
  for db in "${dbs[@]}"; do
    if grep -rhwF "$db" "$root" "${inc[@]}" 2>/dev/null | head -200 | grep -viE "user|login" | grep -q .; then keep+=("$db")
    else warn+=("$db is only used as a MySQL user name here, so it is not moved as a database"); fi
  done
  dbs=("${keep[@]}")
  dbbytes=0; users=()
  for db in "${dbs[@]}"; do
    [[ "$db" =~ ^[A-Za-z0-9_$-]+$ ]] || { block+=("unusual database name: $db"); continue; }
    dbbytes=$(( dbbytes + $(mysql -N -e "select coalesce(sum(data_length+index_length),0) from information_schema.tables where table_schema='$db'") ))
    mapfile -t -O "${#users[@]}" users < <(mysql -N -e "select concat(User,'@',Host) from mysql.db where replace(Db,'\\\\_','_')='$db' and User<>''")
  done
  [ ${#users[@]} -eq 0 ] || mapfile -t users < <(printf '%s\n' "${users[@]}" | sort -u)
  # a database that other sites also use can't move with this one
  if [ ${#dbs[@]} -gt 0 ]; then
    local others
    others=$(timeout 120 grep -rHwF -f <(printf '%s\n' "${dbs[@]}") "$base" --include='*.php' --include='.env' --include='*.ini' 2>/dev/null \
             | grep -viE "user|login" | cut -d: -f1 | grep -v "^$root/" | sed "s#^$base/##; s#/.*##" | sort -u | head -5 | tr '\n' ' ' || true)
    [ -z "$others" ] || block+=("its database is also used by: $others— move those together or split the database first")
  fi
  cron=$(crontab -u "$u" -l 2>/dev/null | grep -v '^[[:space:]]*#' | cron_of_site || true)
  ssl=0; [ -s "$PANEL_SSL/$d/fullchain.pem" ] && ssl=1
  # things that may still point at this server
  local x
  x=$(grep -rhoE "$base/[A-Za-z0-9._-]+" "$root" --include='*.php' 2>/dev/null | sort -u | grep -vxF "$root" | sed "s#^$base/##" | head -5 | tr '\n' ' ' || true)
  [ -z "$x" ] || warn+=("uses files from other site folders that stay here: $x")
  x=$(grep -rlF "$(server_ip)" "$root" --include='*.php' --include='*.js' --include='.env' 2>/dev/null | head -3 | sed "s#^$root/##" | tr '\n' ' ' || true)
  [ -z "$x" ] || warn+=("this server's IP address is written in: $x")
  x=$(grep -rhoE "(127\.0\.0\.1|localhost):[0-9]{2,5}" "$root" --include='*.php' --include='*.js' --include='*.py' 2>/dev/null | grep -vE ':(3306|80|443)$' | sort -u | head -3 | tr '\n' ' ' || true)
  [ -z "$x" ] || warn+=("talks to a local service ($x) — make sure it also runs on $srv")
  dns_points_here "$d" || warn+=("DNS of $d points to '$(dns_a "$d")', not to this server")
  # the other server
  local rinfo
  rinfo=$(node_ssh "$srv" "df -B1 --output=avail /home | tail -1; test -s /root/.namecheap/config && echo NCAPI; test -f /etc/panel/vhosts/$d.conf && echo SITE; test -f $MOVES/$d.json && grep -q '\"status\":\"forwarding\"' $MOVES/$d.json && echo FORWARDED; for db in ${dbs[*]:-}; do mysql -N -e \"select concat('DB:',count(*)) from information_schema.tables where table_schema='\$db'\"; done" 2>/dev/null) \
    || { block+=("can't reach $srv ($rip)"); return 0; }
  local free; free=$(echo "$rinfo" | head -1)
  [ -s /root/.namecheap/config ] || grep -q NCAPI <<<"$rinfo" || warn+=("no Namecheap API on either server: change the DNS by hand after the move")
  [ "$free" -gt $(( (size + dbbytes) * 2 + 1073741824 )) ] || block+=("not enough disk space on $srv")
  if ! grep -q FORWARDED <<<"$rinfo"; then
    grep -q SITE <<<"$rinfo" && block+=("$srv already has a site $d")
    grep -q 'DB:[1-9]' <<<"$rinfo" && block+=("$srv already has data in a database with the same name")
  fi
  return 0
}
human() { numfmt --to=iec --suffix=B "${1:-0}" 2>/dev/null || echo "${1:-0} B"; }
pause_estimate() { echo $(( 10 + dbbytes / 15000000 )); }   # seconds: final file pass + database import at ~15 MB/s

plan() {
  gather "$1" "$2"
  if [ "${3:-}" = --json ]; then
    D="$d" SRV="$srv" RIP="$rip" ROOT="$root" SIZE="$size" DBB="$dbbytes" PAUSE="$(pause_estimate)" SSL="$ssl" \
    DBS="$(printf '%s\n' "${dbs[@]}")" USERS="$(printf '%s\n' "${users[@]}")" CRON="$cron" \
    WARN="$(printf '%s\n' "${warn[@]}")" BLOCK="$(printf '%s\n' "${block[@]}")" python3 -c '
import json, os
L = lambda k: [x for x in os.environ.get(k, "").split("\n") if x]
print(json.dumps({"domain": os.environ["D"], "server": os.environ["SRV"], "ip": os.environ["RIP"], "folder": os.environ["ROOT"],
  "files_bytes": int(os.environ["SIZE"] or 0), "db_bytes": int(os.environ["DBB"] or 0), "pause_seconds": int(os.environ["PAUSE"]),
  "ssl": os.environ["SSL"] == "1", "databases": L("DBS"), "mysql_users": L("USERS"), "cron": L("CRON"),
  "warnings": L("WARN"), "blockers": L("BLOCK")}))'
    return
  fi
  echo "Move $d -> $srv ($rip)"
  echo "  folder:     $root ($(human "$size"))"
  echo "  databases:  ${dbs[*]:-none} ($(human "$dbbytes"))"
  echo "  MySQL users: ${users[*]:-none}"
  echo "  SSL:        $([ $ssl = 1 ] && echo 'copied along' || echo 'none')"
  echo "  cron jobs:  $( [ -n "$cron" ] && echo "$(wc -l <<<"$cron") move along" || echo none)"
  echo "  pause:      about $(pause_estimate) seconds during the final copy"
  local w; for w in "${warn[@]}"; do echo "  ! $w"; done
  for w in "${block[@]}"; do echo "  ✗ $w"; done
  [ ${#block[@]} -eq 0 ] && echo "ready: panel-move-site start $d $srv" || exit 2
}

# ---------- state shown in the panel ----------
state() {   # status step message [extra json fields]
  local f="$MOVES/$d.json" started
  started=$(grep -o '"started":"[^"]*"' "$f" 2>/dev/null | head -1 | cut -d'"' -f4 || true); [ -n "$started" ] || started=$(date -u '+%F %T')
  printf '{"domain":"%s","server":"%s","ip":"%s","user":"%s","folder":"%s","databases":"%s","status":"%s","step":%s,"steps":%s,"message":"%s","started":"%s","updated":"%s"%s}\n' \
    "$d" "$srv" "$rip" "$u" "$root" "${dbs[*]:-}" "$1" "$2" "$STEPS" "${3//\"/\'}" "$started" "$(date -u '+%F %T')" "${4:-}" > "$f.tmp"
  chmod 600 "$f.tmp"; mv -f "$f.tmp" "$f"
}
step() { echo "[$(date '+%T')] $1/$STEPS $2"; state running "$1" "$2"; log "$d -> $srv: $2"; }

RSH() { echo "ssh ${NODE_SSH_OPTS[*]}"; }
copy_files() { rsync -aH --delete --stats -e "$(RSH)" "$root/" "root@$rip:$root/" | grep -E 'Number of regular files transferred|Total transferred file size' || true; }
users_sql() {
  local ua U H s
  for ua in "${users[@]}"; do
    U=${ua%@*}; H=${ua##*@}
    [[ "$U" =~ ^[A-Za-z0-9_.-]+$ && "$H" =~ ^[A-Za-z0-9_.%:-]+$ ]] || continue
    s=$(mysql -N -r -e "SET print_identified_with_as_hex=ON; SHOW CREATE USER '$U'@'$H'")
    echo "${s/CREATE USER /CREATE USER IF NOT EXISTS };"
    echo "${s/CREATE USER /ALTER USER };"
    mysql -N -r -e "SHOW GRANTS FOR '$U'@'$H'" | sed 's/$/;/'
  done
}
copy_db() {   # $1 db, $2 = fresh → empty the copy there first
  local db=$1 cs co
  read -r cs co < <(mysql -N -e "select default_character_set_name, default_collation_name from information_schema.schemata where schema_name='$db'")
  if [ "${2:-}" = fresh ]; then node_ssh "$srv" "mysql -e 'DROP DATABASE IF EXISTS \`$db\`; CREATE DATABASE \`$db\` CHARACTER SET $cs COLLATE $co'"
  else node_ssh "$srv" "mysql -e 'CREATE DATABASE IF NOT EXISTS \`$db\` CHARACTER SET $cs COLLATE $co'"; fi
  mysqldump --single-transaction --quick --routines --triggers --events --hex-blob --set-gtid-purged=OFF --no-tablespaces "$db" \
    | gzip -1 | node_ssh "$srv" "gunzip | mysql '$db'"
}
extra_file() { echo "$EXTRA/$d.conf"; }
own_extra() { local f; f=$(extra_file); if [ -f "$f.premove" ]; then cat "$f.premove"; elif [ -f "$f" ] && ! grep -q '^# panel-move-site' "$f"; then cat "$f"; fi; }
maintenance_on() {
  local f; f=$(extra_file)
  [ -f "$f.premove" ] || { if [ -f "$f" ]; then cp -p "$f" "$f.premove"; else : > "$f.premove"; fi; }
  cat > "$f" <<M
# panel-move-site: final copy to $srv in progress — visitors see a short "back in a moment" page
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/\.well-known/
RewriteRule ^ - [R=503,L]
ErrorDocument 503 "<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'><title>One moment</title><body style='font:17px system-ui,sans-serif;text-align:center;padding:14vh 20px;color:#333'><h1>Back in a moment</h1><p>We are moving this site to a faster server. Please refresh in a minute.</p>"
Header always set Retry-After "60"
M
  apachectl -t >/dev/null 2>&1 && systemctl reload httpd
}
forward_on() {
  local f proto=http ws=ws; f=$(extra_file); [ "$ssl" = 1 ] && { proto=https; ws=wss; }
  { echo "# panel-move-site: $d moved to $srv ($rip) on $(date -u '+%F %T') UTC. This server forwards every visitor there"
    echo "# until DNS has switched everywhere. Ends with: panel-move-site finish $d"
    [ "$proto" = https ] && printf 'SSLProxyEngine on\nSSLProxyVerify none\nSSLProxyCheckPeerName off\nSSLProxyCheckPeerCN off\nSSLProxyCheckPeerExpire off\n'
    echo "ProxyPreserveHost On"
    echo "ProxyTimeout 300"
    printf '<Location /connection/websocket>\n    ProxyPass %s://%s/connection/websocket\n</Location>\n' "$ws" "$rip"
    echo "ProxyPass / $proto://$rip/"
    echo "ProxyPassReverse / $proto://$rip/"
  } > "$f"
  apachectl -t >/dev/null 2>&1 && systemctl reload httpd
}
restore_here() {   # undo the pause: the site runs here again
  local f; f=$(extra_file)
  if [ -f "$f.premove" ]; then if [ -s "$f.premove" ]; then mv -f "$f.premove" "$f"; else rm -f "$f" "$f.premove"; fi; fi
  cron_restore
  apachectl -t >/dev/null 2>&1 && systemctl reload httpd
}
# a site's cron lines: they mention its folder, or call "panel-cron-run <domain> …"
cron_of_site() { grep -F -e "$root/" -e "$root " -e "$root;" -e "$root'" -e "$root\"" -e "panel-cron-run $d "; }
cron_mark() {      # comment the site's cron lines here: they now run on the other server
  [ -n "$cron" ] || return 0
  local cur; cur=$(crontab -u "$u" -l 2>/dev/null || true)
  CRON="$cron" TAG="#moved-to:$srv " python3 -c '
import os, sys
mine = set(l for l in os.environ["CRON"].split("\n") if l)
for l in sys.stdin.read().splitlines():
    print(os.environ["TAG"] + l if l in mine else l)' <<<"$cur" | crontab -u "$u" -
}
cron_restore() { local cur; cur=$(crontab -u "$u" -l 2>/dev/null || true); grep -q "^#moved-to:$srv " <<<"$cur" || return 0; sed "s/^#moved-to:$srv //" <<<"$cur" | crontab -u "$u" -; }

run_move() {
  local nodns="${3:-}"
  gather "$1" "$2"
  [ ${#block[@]} -eq 0 ] || { state failed 0 "${block[0]}"; die "${block[0]}"; }
  exec 9>"/run/panel-move-$d.lock"; flock -n 9 || die "a move of $d is already running"
  local phase=copy
  trap 'rc=$?; if [ $rc -ne 0 ]; then
      if [ "$phase" = forwarding ]; then state forwarding 7 "Moved and forwarding, but the DNS step failed — point the A records of $d to $rip"; log "$d -> $srv: moved, DNS step failed"
      else [ "$phase" = paused ] && { restore_here; echo "the site runs here again (nothing switched)"; }
           state failed 0 "Failed — see the log. The site still runs here."; log "$d -> $srv: FAILED"; fi; fi' EXIT
  step 1 "Preparing $srv"
  # sites set up by an older panel version lack the include for per-site settings (pause page, forwarding): add it now
  grep -q "IncludeOptional $EXTRA/$d.conf" "$(site_conf "$d")" || /opt/panel/bin/panel-site-add "$d" "$root" "$u" >/dev/null
  grep -q "IncludeOptional $EXTRA/$d.conf" "$(site_conf "$d")" || die "the web server config of $d can't take per-site settings"
  node_ssh "$srv" "id $u >/dev/null && install -d -o $u -g $u -m 750 '$root'"
  step 2 "Copying files while the site stays online ($(human "$size"))"
  copy_files
  step 3 "Creating databases and MySQL users on $srv"
  [ ${#users[@]} -eq 0 ] || users_sql | node_ssh "$srv" mysql
  local db
  for db in "${dbs[@]}"; do echo "  $db (first copy)"; copy_db "$db"; done
  step 4 "Copying SSL certificate and web server settings"
  if [ "$ssl" = 1 ]; then
    tar -czf - -C / "etc/panel/ssl/$d" $( [ -d "/etc/letsencrypt/live/$d" ] && echo "etc/letsencrypt/live/$d etc/letsencrypt/archive/$d etc/letsencrypt/renewal/$d.conf" ) | node_ssh "$srv" 'tar -xzf - -C /'
    [ -d /etc/letsencrypt/accounts ] && tar -czf - -C / etc/letsencrypt/accounts | node_ssh "$srv" 'tar -xzf - -C / --skip-old-files'
  fi
  node_ssh "$srv" "/opt/panel/bin/panel-site-add '$d' '$root' '$u' >/dev/null"
  step 5 "Pausing the site for the final copy (about $(pause_estimate) s)"
  phase=paused
  maintenance_on; cron_mark; sleep 3
  copy_files
  [ -d "/var/lib/panel/php/$u/session" ] && rsync -a --ignore-existing -e "$(RSH)" "/var/lib/panel/php/$u/session/" "root@$rip:/var/lib/panel/php/$u/session/" || true
  for db in "${dbs[@]}"; do echo "  $db (final copy)"; copy_db "$db" fresh; done
  step 6 "Switching the site on at $srv"
  own_extra | node_ssh "$srv" "/opt/panel/bin/panel-move-site _accept '$d' '$root' '$u'"
  [ -z "$cron" ] || echo "$cron" | node_ssh "$srv" "/opt/panel/bin/panel-move-site _cron '$u' '$root'"
  forward_on; phase=forwarding
  local code; code=$(curl -sk -o /dev/null -m 20 -w '%{http_code}' --resolve "$d:443:$rip" --resolve "$d:80:$rip" "$([ "$ssl" = 1 ] && echo https || echo http)://$d/" || true)
  echo "  $srv answers for $d with HTTP $code"
  step 7 "Pointing DNS to $srv"
  local dnsmsg
  if [ "$nodns" = --no-dns ]; then dnsmsg="DNS not changed (--no-dns): point the A records of $d to $rip"
  else
    # the Namecheap API only answers the server(s) whitelisted there: use this one, else the new one
    local out=NOAPI ncmd="/opt/panel/bin/panel-namecheap-dns move '$(server_ip)' '$rip' --apply --only '$d'"
    if [ -s /root/.namecheap/config ]; then out=$(bash -c "$ncmd" 2>&1 || true)
    elif node_ssh "$srv" 'test -s /root/.namecheap/config' 2>/dev/null; then out=$(node_ssh "$srv" "$ncmd" 2>&1 || true); fi
    echo "$out" | sed 's/^/  /'
    if grep -q "CHANGED" <<<"$out"; then dnsmsg="DNS changed at Namecheap"
    elif [ "$out" = NOAPI ]; then dnsmsg="no Namecheap API on either server: change the A records of $d (and www) to $rip at your DNS provider"
    elif grep -q "not at Namecheap\|excluded\|expired" <<<"$out"; then dnsmsg="DNS is not managed here: change the A records of $d (and www) to $rip"
    else dnsmsg="DNS change unclear — check the A records of $d point to $rip"; fi
  fi
  echo "  $dnsmsg"
  trap - EXIT
  step 8 "Done"
  state forwarding 8 "Moved. $dnsmsg. This server forwards visitors until DNS has switched everywhere — finish it after a day." ",\"dns\":\"${dnsmsg//\"/\'}\",\"http\":\"$code\""
  log "$d -> $srv: moved ($dnsmsg)"
  echo "done: $d now runs on $srv. Forwarding from here stays on until: panel-move-site finish $d"
}

# ---------- receiving side ----------
accept() {   # stdin: the site's own extra Apache settings ('' = none)
  d="$1"; root="$2"; u="$3"
  valid_domain "$d" && valid_user "$u" || die "bad arguments"
  local f="$EXTRA/$d.conf" content; content=$(cat)
  if [ -n "$content" ]; then printf '%s\n' "$content" > "$f"; else rm -f "$f"; fi
  rm -f "$f.premove"
  [ -f "$MOVES/$d.json" ] && mv -f "$MOVES/$d.json" "$MOVES/$d.json.$(date +%s).old"   # it had moved away from here before: it's back now
  /opt/panel/bin/panel-site-add "$d" "$root" "$u" >/dev/null
  # cron lines that were parked here when the site moved away earlier are replaced by the incoming ones
  local cur; cur=$(crontab -u "$u" -l 2>/dev/null || true)
  if grep '^#moved-to:' <<<"$cur" | cron_of_site >/dev/null; then
    awk -v r="$root" -v d="panel-cron-run $d " '!(/^#moved-to:/ && (index($0, r) || index($0, d)))' <<<"$cur" | crontab -u "$u" -
  fi
  log "$d: received"
}
cron_add() { local uu="$1" r="$2" cur add; valid_user "$uu" || die "bad user"; add=$(cat); cur=$(crontab -u "$uu" -l 2>/dev/null || true)
  { [ -z "$cur" ] || echo "$cur"; while IFS= read -r l; do [ -n "$l" ] && ! grep -qxF "$l" <<<"$cur" && echo "$l"; done <<<"$add"; } | crontab -u "$uu" -; }

status() {
  local f
  if [ -n "${1:-}" ] && [ "$1" != --json ]; then
    valid_domain "$1" || die "invalid domain"; f="$MOVES/$1.json"; [ -f "$f" ] || die "no move of $1 started here"
    if [ "${2:-}" = --json ]; then cat "$f"; else cat "$f"; tail -30 "$PANEL_LOG/move-$1.log" 2>/dev/null; fi; return
  fi
  local out=(); for f in "$MOVES"/*.json; do [ -f "$f" ] && out+=("$(cat "$f")"); done
  local IFS=,; echo "[${out[*]:-}]"
}

finish() {
  d="$1"; valid_domain "$d" || die "invalid domain"
  local f="$MOVES/$d.json"; [ -f "$f" ] && grep -q '"status":"forwarding"' "$f" || die "$d is not a moved site that this server still forwards"
  srv=$(grep -o '"server":"[^"]*"' "$f" | cut -d'"' -f4); rip=$(grep -o '"ip":"[^"]*"' "$f" | cut -d'"' -f4)
  u=$(grep -o '"user":"[^"]*"' "$f" | cut -d'"' -f4); root=$(grep -o '"folder":"[^"]*"' "$f" | cut -d'"' -f4)
  read -r -a dbs <<<"$(grep -o '"databases":"[^"]*"' "$f" | cut -d'"' -f4)"
  dns_points_here "$d" && die "DNS of $d still points to this server — wait until it points to $srv ($rip)"
  local arch="/home/$u/moved/$d-$(date +%F-%H%M)" db
  install -d -o "$u" -g "$u" -m 750 "/home/$u/moved" "$arch"
  for db in "${dbs[@]}"; do
    [[ "$db" =~ ^[A-Za-z0-9_$-]+$ ]] || continue
    mysqldump --single-transaction --quick --routines --triggers --events --hex-blob --set-gtid-purged=OFF --no-tablespaces "$db" | gzip > "$arch/$db.sql.gz"
    mysql -e "DROP DATABASE \`$db\`"; echo "database $db saved to $arch/$db.sql.gz and removed here"
  done
  [ -d "$root" ] && mv "$root" "$arch/files" && echo "files moved to $arch/files"
  chown -R "$u:$u" "$arch"
  rm -f "$(site_conf "$d")" "$(site_conf "$d").bak" "$EXTRA/$d.conf" "$EXTRA/$d.conf.premove"
  certbot delete --cert-name "$d" --non-interactive >/dev/null 2>&1 || true; rm -rf "${PANEL_SSL:?}/$d"
  local cur; cur=$(crontab -u "$u" -l 2>/dev/null || true)
  if grep "^#moved-to:$srv " <<<"$cur" | cron_of_site >/dev/null; then
    awk -v t="#moved-to:$srv " -v r="$root" -v d="panel-cron-run $d " '!(index($0, t) == 1 && (index($0, r) || index($0, d)))' <<<"$cur" | crontab -u "$u" -
  fi
  [ -x /opt/panel/bin/panel-admin-hosts ] && /opt/panel/bin/panel-admin-hosts
  apachectl -t >/dev/null 2>&1 && systemctl reload httpd
  dbs=(); state finished 8 "Finished: old copy archived in $arch" ",\"archive\":\"$arch\""
  /opt/panel/bin/panel-ssl-status >/dev/null 2>&1 || true   # the Sites page drops it at once
  log "$d: finished, archived to $arch"; echo "finished: $d is only on $srv now; the old copy is in $arch"
}

back() {
  d="$1"; valid_domain "$d" || die "invalid domain"
  local f="$MOVES/$d.json"; [ -f "$f" ] && grep -q '"status":"forwarding"' "$f" || die "$d is not a moved site that this server still forwards"
  srv=$(grep -o '"server":"[^"]*"' "$f" | cut -d'"' -f4)
  node_ssh "$srv" "/opt/panel/bin/panel-move-site start '$d' '$(self_name)'"
}

start() {
  d="${1:-}"; srv="${2:-}"; valid_domain "$d" || die "invalid domain"; node_ip "$srv" >/dev/null || die "unknown server: $srv"
  [ "${3:-}" = "" ] || [ "${3:-}" = --no-dns ] || die "unknown option ${3:-}"
  local unit="panel-move-${d//./-}"
  systemctl is-active --quiet "$unit" && die "a move of $d is already running"
  rip=$(node_ip "$srv"); u=""; root=""; dbs=()
  [ -f "$MOVES/$d.json" ] && mv -f "$MOVES/$d.json" "$MOVES/$d.json.$(date +%s).old"
  state queued 0 "Starting"
  systemd-run --quiet --unit="$unit" --collect /bin/bash -c "exec /opt/panel/bin/panel-move-site run '$d' '$srv' ${3:-} >> '$PANEL_LOG/move-$d.log' 2>&1"
  echo "move of $d to $srv started — follow it in the panel or: tail -f $PANEL_LOG/move-$d.log"
}

if [ "${1:-}" = on ]; then   # the same for a site that lives on a connected server (so one panel can move sites in any direction)
  srv="${2:-}"; ip=$(node_ip "$srv") || die "unknown server: $srv"; shift 2
  [[ "${1:-}" =~ ^(plan|start|status|finish|back|log)$ ]] || die "not allowed there: ${1:-}"
  exec timeout 170 ssh "${NODE_SSH_OPTS[@]}" "root@$ip" "/opt/panel/bin/panel-move-site $(printf '%q ' "$@")"
fi
case "${1:-}" in
  plan)    plan "${2:-}" "${3:-}" "${4:-}" ;;
  start)   start "${2:-}" "${3:-}" "${4:-}" ;;
  run)     echo "===== $(date -u '+%F %T') move ${2:-} -> ${3:-}"; run_move "${2:-}" "${3:-}" "${4:-}" ;;
  status)  status "${2:-}" "${3:-}" ;;
  finish)  finish "${2:-}" ;;
  back)    back "${2:-}" ;;
  log)     valid_domain "${2:-}" || die "invalid domain"; tail -n 80 "$PANEL_LOG/move-$2.log" 2>/dev/null || true ;;
  _accept) accept "${2:-}" "${3:-}" "${4:-}" ;;
  _cron)   cron_add "${2:-}" "${3:-}" ;;
  *) sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;;
esac
