#!/usr/bin/env bash
# Copyright (c) 2026 HostFog Ltd. All rights reserved.
# Proprietary and confidential. Use is subject to the HostFog licence (LICENSE).
# Unauthorised copying, modification or distribution is prohibited.
# HostFog admin CLI — run "hf-admin help" for every command.
HF=/usr/local/hostfog
cmd="${1:-help}"

help() {
  cat <<'EOF'
HostFog Panel — server commands (run as root)

Admin logins
  hf-admin create-admin               create an admin login for the panel
  hf-admin reset-password <user>      set a new password for a panel login
  hf-admin reset-2fa <user>           switch off two-factor sign-in for a login (lost phone)
  hf-admin list                       list the panel's admin and reseller logins

Control panel data (made every night; accounts, packages, invoices, settings, tickets)
  hf-admin panel-backups              list the copies of the panel's own data
  hf-admin panel-backup               make a copy now
  hf-admin panel-restore <name>       put a copy back (the current data is kept next to it)

DNS and mail
  hf-admin dns-setup                  the DNS records this server's own domain needs (add --check to look them up)
  hf-admin mail-name <name>           use another mail server name, e.g. mx.example.com
  hf-admin mail-autoconfig            (re)create mail-app auto-setup (Outlook, Thunderbird, phones)
  hf-admin ssl-now                    get or renew the panel's SSL certificate now instead of waiting 5 minutes

Separate panels
  hf-admin portals                    show the three panels, whether their DNS points here and has SSL
  hf-admin portals on                 Server Admin at server.<domain>, Control Panel at panel.<domain>,
                                      Reseller Panel at reseller.<domain> (each with its own sign-in)
  hf-admin portals on --admin NAME --customer NAME --reseller NAME    choose the names yourself
  hf-admin portals off                back to one panel for everyone
  hf-admin status-page on [NAME]      the public status page on its own address (default status.<domain>)
  hf-admin status-page off            the status page stays at https://<panel>/status

Repairs
  hf-admin health                     check the whole server (services, config, disk, memory, SSL, clock, mail queue)
  hf-admin apache-fix                 repair and start Apache (port clash, missing log folders, leftover sites)
  hf-admin php-versions               PHP versions this server can install
  hf-admin php-repo                   add the extra PHP versions repository if it supports this Ubuntu release

More servers
  hf-admin node-enable <main IP>      let the main HostFog server add this one as an extra server (--new: new join code)
  hf-admin node-disable               stop being an extra server

Install, update, remove
  sudo bash latest [options]          install, or update an installed panel (see options below)
  hf-admin uninstall                  remove the panel, keep websites, databases and mail running
  hf-admin uninstall --purge          also delete all hosting accounts (asks for a confirmation word)
  hf-admin uninstall --packages       also remove Nginx, Apache, PHP, MariaDB, mail and DNS software (add --yes for scripts)

Installer options
  --hostname panel.example.com        panel address          --email you@example.com    admin email (SSL notices)
  --mail-host mx.example.com          mail server name       --port 8443                panel port
  --ns1 NAME --ns2 NAME               nameserver names       --node 18|20|22|24         Node.js version
  --no-mail                           skip email             --no-dns                   skip the DNS server
  --no-portals                        one panel for everyone instead of Server Admin / Control Panel / Reseller Panel
  --quotas                            hard disk quotas       --licence KEY              paid edition

Logs: /var/log/hostfog-install.log · /var/log/hostfog-*.log · /home/<user>/logs/
EOF
}
agent() {   # the root helper, for the repair commands
  [[ $EUID -eq 0 ]] || { echo "Run as root: sudo hf-admin $cmd"; exit 1; }
  [[ -x "$HF/bin/hf-agent" ]] || { echo "HostFog is not installed here."; exit 1; }
  "$HF/bin/hf-agent" "$@"
}
case "$cmd" in
  help|-h|--help) help;;
  uninstall)       shift; exec "$HF/bin/hf-uninstall" "$@";;
  dns-setup)       shift; exec "$HF/bin/hf-dns-setup" "$@";;
  apache-fix)      agent apache-start;;
  health)          agent health-check | awk -F'|' '$1 ~ /^(ok|warn|bad)$/ {
                     m = ($1 == "ok") ? "\033[32m✔\033[0m" : ($1 == "bad") ? "\033[31m✘\033[0m" : "\033[33m!\033[0m"
                     printf "  %s %-14s %-22s %s%s\n", m, $3, $4, $5, ($6 != "" ? "   (fix in the panel: Server health)" : "")
                     n[$1]++ } END { printf "\n  %d ok · %d warnings · %d problems — the panel'"'"'s Server health page also checks DNS, SSL and backups\n", n["ok"], n["warn"], n["bad"] }';;
  mail-name)       [[ -n "${2:-}" ]] || { echo "Usage: hf-admin mail-name mx.example.com"; exit 1; }; agent mail-name "$2";;
  mail-autoconfig) agent mail-autoconfig;;
  ssl-now)         agent panel-ssl now;;
  status-page)
    case "${2:-}" in
      on)  agent status-page-on ${3:+"$3"};;
      off) agent status-page-off;;
      *)   echo "Usage: hf-admin status-page on [status.example.com] | off"; exit 1;;
    esac;;
  portals)
    sub="${2:-status}"; shift 2 2>/dev/null || shift $#
    pa="" pc="" pr=""
    while [[ $# -gt 0 ]]; do
      case "$1" in
        --admin) pa="$2"; shift 2;; --customer|--client) pc="$2"; shift 2;; --reseller) pr="$2"; shift 2;;
        *) echo "Unknown option $1"; exit 1;;
      esac
    done
    show_portals() {
      local out; out="$(agent portals-status 2>/dev/null)" || exit 1
      if ! grep -q '^PANEL=' <<<"$out"; then echo "Separate panels are off: everyone signs in at the classic panel address. Switch on: hf-admin portals on"; return; fi
      printf '
  %-16s %-34s %-10s %s
' "Panel" "Address" "DNS" "SSL"
      sed -n 's/^PANEL=//p' <<<"$out" | while IFS='|' read -r k n d s; do
        label=$(case "$k" in admin) echo "Server Admin";; client) echo "Control Panel";; reseller) echo "Reseller Panel";; status) echo "Status page";; esac)
        printf '  %-16s %-34s %-10s %s
' "$label" "https://$n" "$( [[ $d == here ]] && echo "ok" || echo "add A")" "$( [[ $s == yes ]] && echo "ok" || echo "after DNS")"
      done
      ip="$(php -r '$c = require "/etc/hostfog/config.php"; echo $c["server_ip"] ?? "";' 2>/dev/null)"
      echo; echo "  "add A": point that name at ${ip:-this server} at your DNS provider; SSL follows by itself within 5 minutes."
      echo "  The classic address keeps working for everyone."
    }
    case "$sub" in
      on)     out="$(agent portals-on "${pa}" "${pc}" "${pr}" 2>&1)" || { echo "$out" | grep -v "^curl"; exit 1; }; show_portals;;
      off)    agent portals-off;;
      status|"") show_portals;;
      *) echo "Usage: hf-admin portals [on|off] [--admin NAME --customer NAME --reseller NAME]"; exit 1;;
    esac;;
  php-versions)    agent php-available | grep -v '^OK' | sed 's/^/PHP /';;
  php-repo)        agent php-repo;;
  panel-restore)
    [[ $EUID -eq 0 ]] || { echo "Run as root: sudo hf-admin $cmd"; exit 1; }
    sudo -u hostfog "/usr/bin/php$(cat /etc/hostfog/php_default 2>/dev/null || echo 8.3)" "$HF/panel/bin/admin.php" "$@" || exit 1
    # fresh connections for the panel, and the database brought up to this version
    for s in /lib/systemd/system/php*-fpm.service; do [[ -e "$s" ]] && systemctl reload "$(basename "$s" .service)" 2>/dev/null; done
    sudo -u hostfog "/usr/bin/php$(cat /etc/hostfog/php_default 2>/dev/null || echo 8.3)" "$HF/panel/bin/migrate.php" >/dev/null 2>&1 || true;;
  create-admin|reset-password|reset-2fa|list|node-enable|node-disable|has-admin|panel-backups|panel-backup)
    exec sudo -u hostfog "/usr/bin/php$(cat /etc/hostfog/php_default 2>/dev/null || echo 8.3)" "$HF/panel/bin/admin.php" "$@";;
  *) echo "Unknown command: $cmd"; echo; help; exit 1;;
esac
