#!/bin/bash
# panel-server — the other servers running Incaine Panel that sites can be moved to.
#   panel-server list [--json]               this server and every connected one, with live numbers
#   panel-server add <name> <ip> [<this-name>]
#                                            connect a server (give its root password on stdin the first time; afterwards
#                                            the two servers use keys). Works both ways, so sites can also move back.
#   panel-server remove <name>
#   panel-server name [<name>]               show / set the name of this server
# internal: self [--json] · trust <name> <ip> · peers
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
install -d -m 700 "$PANEL_NODES"

ensure_key() { [ -s "$NODE_KEY" ] || ssh-keygen -q -t ed25519 -N '' -C "incaine-panel@$(self_name)" -f "$NODE_KEY"; chmod 600 "$NODE_KEY"; }
set_name() {
  valid_node "$1" || die "server name: lowercase letters, digits and - (max 30)"
  if grep -q '^SERVER_NAME=' /etc/panel/panel.conf 2>/dev/null; then sed -i "s/^SERVER_NAME=.*/SERVER_NAME=$1/" /etc/panel/panel.conf
  else echo "SERVER_NAME=$1" >> /etc/panel/panel.conf; fi
  SERVER_NAME=$1
}
register() { printf 'HOST=%s\nADDED=%s\n' "$2" "$(date -u +%F)" > "$PANEL_NODES/$1.conf"; chmod 600 "$PANEL_NODES/$1.conf"; }
allow_key() {   # let <ip> log in here with <pubkey> (root, only from that address)
  install -d -m 700 /root/.ssh; touch /root/.ssh/authorized_keys; chmod 600 /root/.ssh/authorized_keys
  grep -qF "$2" /root/.ssh/authorized_keys || echo "from=\"$1\",no-agent-forwarding,no-X11-forwarding $2" >> /root/.ssh/authorized_keys
}
# Visitors forwarded by one of our servers during a move keep their real IP address (logins, rate limits, bans).
peers() {
  local f=/etc/httpd/conf.d/01-panel-peers.conf ips="" c
  for c in "$PANEL_NODES"/*.conf; do [ -f "$c" ] && ips+=" $(. "$c"; echo "$HOST")"; done
  if [ -n "$ips" ]; then
    printf '# managed by panel-server: real visitor addresses for requests our other servers forward during a site move\nRemoteIPHeader X-Forwarded-For\nRemoteIPInternalProxy%s\n' "$ips" > "$f"
  else rm -f "$f"; fi
  if apachectl -t >/dev/null 2>&1; then systemctl reload httpd; else rm -f "$f"; systemctl reload httpd; die "apache config test failed"; fi
}

# One of this server's sites (valid certificate, DNS pointing here) that the browser can time a tiny request to.
probe_host() {
  local c=/var/lib/panel/probe-host f d
  if [ -s "$c" ] && [ -n "$(find "$c" -mmin -60 2>/dev/null)" ]; then cat "$c"; return; fi
  for f in "$PANEL_VHOSTS"/*.conf; do
    d=$(basename "$f" .conf)
    grep -qs '"status":"forwarding"' "/var/lib/panel/moves/$d.json" && continue   # moved away: only forwarded from here
    [ -s "$PANEL_SSL/$d/fullchain.pem" ] && [ "$(cert_days "$PANEL_SSL/$d/fullchain.pem")" -gt 3 ] && dns_points_here "$d" && { echo "$d" > "$c"; echo "$d"; return; }
  done
  : > "$c"
}
# Round trip from here to every connected server (ms, average of 3), as a JSON object.
peer_pings() {
  local tmp c n ip out=() pg
  tmp=$(mktemp -d)
  for c in "$PANEL_NODES"/*.conf; do
    [ -f "$c" ] || continue; n=$(basename "$c" .conf); ip=$(. "$c"; echo "$HOST")
    ( ping -n -q -c 3 -i 0.2 -W 1 "$ip" 2>/dev/null | awk -F/ '/^rtt|^round-trip/ {print $5}' > "$tmp/$n" ) &
  done
  wait
  for c in "$PANEL_NODES"/*.conf; do
    [ -f "$c" ] || continue; n=$(basename "$c" .conf); pg=$(cat "$tmp/$n" 2>/dev/null || true); [[ "$pg" =~ ^[0-9.]+$ ]] || pg=null
    out+=("\"$n\":$pg")
  done
  rm -rf "$tmp"; local IFS=,; echo "{${out[*]:-}}"
}

self_json() {
  local load mt ma dt df sites ver up t busy iow a1 b1 c1 d1 e1 f1 g1 h1 a2 b2 c2 d2 e2 f2 g2 h2 x
  read -r load x < /proc/loadavg
  mt=$(awk '/^MemTotal/{print $2*1024}' /proc/meminfo); ma=$(awk '/^MemAvailable/{print $2*1024}' /proc/meminfo)
  read -r dt df < <(df -B1 --output=size,avail /home | tail -1)
  sites=$(find "$PANEL_VHOSTS" -maxdepth 1 -name '*.conf' 2>/dev/null | wc -l)
  ver=$(cat /opt/panel/VERSION 2>/dev/null || echo "?"); up=$(awk '{print int($1)}' /proc/uptime)
  local pings probe; peer_pings > /run/panel-pings.$$ & probe=$(probe_host)
  read -r x a1 b1 c1 d1 e1 f1 g1 h1 x < /proc/stat; sleep 0.5; read -r x a2 b2 c2 d2 e2 f2 g2 h2 x < /proc/stat
  wait; pings=$(cat /run/panel-pings.$$ 2>/dev/null || echo '{}'); rm -f /run/panel-pings.$$
  t=$(( (a2+b2+c2+d2+e2+f2+g2+h2) - (a1+b1+c1+d1+e1+f1+g1+h1) )); [ "$t" -gt 0 ] || t=1
  busy=$(( 100 * ((a2+b2+c2+f2+g2+h2) - (a1+b1+c1+f1+g1+h1)) / t )); iow=$(( 100 * (e2-e1) / t ))
  printf '{"name":"%s","ip":"%s","cpus":%s,"load":%s,"cpu":%s,"iowait":%s,"mem_total":%s,"mem_avail":%s,"disk_total":%s,"disk_free":%s,"sites":%s,"version":"%s","uptime":%s,"probe":"%s","steal":%s,"guard":%s,"pings":%s}\n' \
    "$(self_name)" "$(server_ip)" "$(nproc)" "$load" "$busy" "$iow" "$mt" "$ma" "$dt" "$df" "$sites" "$ver" "$up" "$probe" "$(( 100 * (h2-h1) / t ))" \
    "$(if [ -f /run/panel/guard-2 ]; then echo 2; elif [ -f /run/panel/guard-1 ]; then echo 1; else echo 0; fi)" "${pings:-{\}}"
}

list() {
  local tmp c n ip r out=()
  tmp=$(mktemp -d); trap 'rm -rf "$tmp"' RETURN
  self_json > "$tmp/.self" &
  for c in "$PANEL_NODES"/*.conf; do
    [ -f "$c" ] || continue; n=$(basename "$c" .conf); ip=$(. "$c"; echo "$HOST")
    ( timeout 20 ssh "${NODE_SSH_OPTS[@]}" "root@$ip" /opt/panel/bin/panel-server self 2>/dev/null | tail -1 > "$tmp/$n" ) &
  done
  wait
  r=$(cat "$tmp/.self"); out+=("{\"self\":true,\"ok\":true,\"key\":\"\",${r#\{}")
  for c in "$PANEL_NODES"/*.conf; do
    [ -f "$c" ] || continue; n=$(basename "$c" .conf); ip=$(. "$c"; echo "$HOST"); r=$(cat "$tmp/$n" 2>/dev/null || true)
    if [[ "$r" == \{* ]]; then out+=("{\"self\":false,\"ok\":true,\"key\":\"$n\",${r#\{}")
    else out+=("{\"self\":false,\"ok\":false,\"key\":\"$n\",\"name\":\"$n\",\"ip\":\"$ip\"}"); fi
  done
  local IFS=,; echo "[${out[*]}]"
}

add() {
  local n="${1:-}" ip="${2:-}" me="${3:-}" myip pub pw ru rpub
  valid_node "$n" || die "server name: lowercase letters, digits and - (max 30)"
  [[ "$ip" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || die "IP address like 203.0.113.7"
  myip=$(server_ip); [ -n "$myip" ] || die "could not find this server's public IP"
  [ "$ip" != "$myip" ] || die "$ip is this server"
  [ -z "$me" ] || set_name "$me"
  [ "$n" != "$(self_name)" ] || die "this server is already called $n — pick another name"
  ensure_key; pub=$(cat "$NODE_KEY.pub")
  if ! ssh "${NODE_SSH_OPTS[@]}" "root@$ip" true 2>/dev/null; then
    IFS= read -r pw || true
    [ -n "$pw" ] || die "first connection to $ip: the root password is needed once"
    command -v sshpass >/dev/null || dnf -y -q install sshpass >/dev/null 2>&1 || die "could not install sshpass"
    SSHPASS="$pw" sshpass -e ssh -o UserKnownHostsFile="$NODE_KH" -o StrictHostKeyChecking=accept-new -o PubkeyAuthentication=no \
      -o PreferredAuthentications=password,keyboard-interactive -o ConnectTimeout=10 -o LogLevel=ERROR "root@$ip" \
      "umask 077; mkdir -p ~/.ssh; touch ~/.ssh/authorized_keys; grep -qF '$pub' ~/.ssh/authorized_keys || echo 'from=\"$myip\",no-agent-forwarding,no-X11-forwarding $pub' >> ~/.ssh/authorized_keys" \
      || die "could not log in to $ip as root with that password (wrong password, or password logins switched off there)"
    ssh "${NODE_SSH_OPTS[@]}" "root@$ip" true || die "key login to $ip failed after setup"
  fi
  ssh "${NODE_SSH_OPTS[@]}" "root@$ip" 'test -x /opt/panel/bin/panel-move-site' \
    || die "$ip has no (or an older) Incaine Panel — install/update it there first: curl -fsSL https://incaine.com/panel/install.sh | bash"
  ru=$(ssh "${NODE_SSH_OPTS[@]}" "root@$ip" '. /etc/panel/panel.conf 2>/dev/null; echo "${PANEL_USER:-web}"')
  [ "$ru" = "$PANEL_USER" ] || die "hosting user differs (here: $PANEL_USER, there: $ru) — sites can only move between servers with the same hosting user"
  register "$n" "$ip"
  # the other server learns its name and gets a key to this one (for moves in the other direction)
  rpub=$(ssh "${NODE_SSH_OPTS[@]}" "root@$ip" "/opt/panel/bin/panel-server name '$n' >/dev/null && /opt/panel/bin/panel-server trust '$(self_name)' '$myip'" | tail -1)
  [[ "$rpub" == ssh-ed25519\ * ]] || die "the other server did not return its key"
  allow_key "$ip" "$rpub"
  # MySQL passwords copied from here must work there (old mysql_native_password hashes)
  if mysql -N -e "select plugin_status from information_schema.plugins where plugin_name='mysql_native_password'" 2>/dev/null | grep -q ACTIVE; then
    ssh "${NODE_SSH_OPTS[@]}" "root@$ip" 'mysql -N -e "select plugin_status from information_schema.plugins where plugin_name=\"mysql_native_password\"" | grep -q ACTIVE || { printf "[mysqld]\nmysql_native_password=ON\n" > /etc/my.cnf.d/panel-native-password.cnf; systemctl restart mysqld; echo "enabled mysql_native_password there"; }'
  fi
  ssh "${NODE_SSH_OPTS[@]}" "root@$ip" 'command -v rsync >/dev/null || dnf -y -q install rsync >/dev/null'
  command -v rsync >/dev/null || dnf -y -q install rsync >/dev/null
  peers; ssh "${NODE_SSH_OPTS[@]}" "root@$ip" /opt/panel/bin/panel-server peers
  log "server connected: $n ($ip)"
  echo "connected: $n ($ip) — this server is '$(self_name)' there"
}

remove() {
  local n="${1:-}" ip
  ip=$(node_ip "$n") || die "unknown server: $n"
  ls /var/lib/panel/moves/*.json >/dev/null 2>&1 && grep -l "\"server\":\"$n\"" /var/lib/panel/moves/*.json 2>/dev/null | xargs -r grep -l '"status":"\(running\|forwarding\)"' | grep -q . \
    && die "a site is moving to / forwarded to $n — finish that first"
  rm -f "$PANEL_NODES/$n.conf"
  sed -i "\#^from=\"$ip\",no-agent-forwarding,no-X11-forwarding ssh-ed25519 .* incaine-panel@#d" /root/.ssh/authorized_keys 2>/dev/null || true
  peers; log "server removed: $n ($ip)"; echo "removed $n"
}

case "${1:-}" in
  list)   list ;;
  self)   self_json ;;
  add)    add "${2:-}" "${3:-}" "${4:-}" ;;
  remove) remove "${2:-}" ;;
  name)   if [ -n "${2:-}" ]; then set_name "$2"; fi; self_name ;;
  trust)  valid_node "${2:-}" || die "bad name"; [[ "${3:-}" =~ ^[0-9.]+$ ]] || die "bad ip"; ensure_key; register "$2" "$3"; cat "$NODE_KEY.pub" ;;
  peers)  peers ;;
  sites)  # this server's sites with SSL/DNS status and usage (for the Sites page of the other servers)
    fw=$(for f in $(grep -ls '"status":"forwarding"' /var/lib/panel/moves/*.json 2>/dev/null); do
           printf '{"d":"%s","to":"%s"}\n' "$(basename "$f" .json)" "$(grep -o '"server":"[^"]*"' "$f" | head -1 | cut -d'"' -f4)"; done | paste -sd, -)
    paused=$(/opt/panel/bin/panel-site-pause list 2>/dev/null | sed 's/.*/"&"/' | paste -sd, - || true)
    printf '{"name":"%s","ip":"%s","paused":[%s],"ssl":%s,"usage":%s,"forwarding":[%s]}\n' "$(self_name)" "$(server_ip)" "$paused" \
      "$({ tr -d '\n' < /var/lib/panel/ssl-status.json; } 2>/dev/null || echo null)" "$({ tr -d '\n' < /var/lib/panel/usage.json; } 2>/dev/null || echo null)" "$fw" ;;
  sites-all)   # the same from every connected server, as one JSON object {name: {...}}
    tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
    for c in "$PANEL_NODES"/*.conf; do
      [ -f "$c" ] || continue; n=$(basename "$c" .conf)
      ( timeout 20 ssh "${NODE_SSH_OPTS[@]}" "root@$(. "$c"; echo "$HOST")" /opt/panel/bin/panel-server sites 2>/dev/null > "$tmp/$n" ) &
    done
    wait; out=()
    for c in "$PANEL_NODES"/*.conf; do
      [ -f "$c" ] || continue; n=$(basename "$c" .conf); r=$(tr -d '\n' < "$tmp/$n" 2>/dev/null || true)
      [[ "$r" == \{* ]] || r='{"unreachable":true}'
      out+=("\"$n\":$r")
    done
    (IFS=,; echo "{${out[*]:-}}") ;;
  *) sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;;
esac
