#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

usage() {
  cat <<'USAGE'
Usage:
  sudo bash scripts/install-ops.sh [--enable-now] [--with-https]

Installs production operations for Vexon Pool:
  - systemd services for node, peer, stratum, backend loops, and optional wallet
  - logrotate policy for pool, stratum, node, wallet, and monitor logs
  - daily encrypted/private production backup timer
  - health monitor timer with optional automatic Vexon service restart
  - SSL renewal timer when certbot is installed

Options:
  --enable-now   Stop screen sessions and start the systemd stack now.
  --with-https   Run scripts/install-https.sh before installing SSL renewal timer.
  -h, --help     Show this help.
USAGE
}

enable_now=0
with_https=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --enable-now)
      enable_now=1
      ;;
    --with-https)
      with_https=1
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
  shift
done

if [[ "$(id -u)" != "0" ]]; then
  echo "Run as root: sudo bash scripts/install-ops.sh" >&2
  exit 1
fi

if [[ ! -f .env ]]; then
  echo "Missing .env. Copy .env.example to .env and edit it first." >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
source .env
set +a

VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_LOG_DIR="${VEX_LOG_DIR:-$VEX_POOL_ROOT/log}"
VEX_STRATUM_CONFIG_DIR="${VEX_STRATUM_CONFIG_DIR:-$VEX_POOL_ROOT/stratum-config}"
VEX_NODE_APPDATA="${VEX_NODE_APPDATA:-/root/.vexond}"
VEX_WALLET_APPDATA="${VEX_WALLET_APPDATA:-/root/.vexonwallet}"
VEX_PEER_APPDATA="${VEX_PEER_APPDATA:-/root/.vexond-peer}"
VEX_BACKUP_DIR="${VEX_BACKUP_DIR:-/root/vexon-pool-backups}"
VEX_BACKUP_ON_CALENDAR="${VEX_BACKUP_ON_CALENDAR:-*-*-* 02:20:00}"
VEX_MONITOR_INTERVAL_SECONDS="${VEX_MONITOR_INTERVAL_SECONDS:-300}"
VEX_SSL_RENEW_ON_CALENDAR="${VEX_SSL_RENEW_ON_CALENDAR:-*-*-* 03:20:00}"
VEX_LOG_RETENTION_DAYS="${VEX_LOG_RETENTION_DAYS:-14}"

if ! [[ "$VEX_MONITOR_INTERVAL_SECONDS" =~ ^[0-9]+$ ]] || (( VEX_MONITOR_INTERVAL_SECONDS < 60 )); then
  echo "VEX_MONITOR_INTERVAL_SECONDS must be an integer >= 60" >&2
  exit 1
fi

if ! [[ "$VEX_LOG_RETENTION_DAYS" =~ ^[0-9]+$ ]] || (( VEX_LOG_RETENTION_DAYS < 1 )); then
  echo "VEX_LOG_RETENTION_DAYS must be a positive integer" >&2
  exit 1
fi

chmod 600 .env
install -d -m 775 "$VEX_LOG_DIR"
install -d -m 700 "$VEX_BACKUP_DIR"

chmod +x scripts/*.sh

if (( with_https )); then
  bash scripts/install-https.sh
fi

if (( enable_now )); then
  bash scripts/install-systemd.sh --enable-now
else
  bash scripts/install-systemd.sh
fi

cat > /etc/logrotate.d/vexon-pool <<EOF
$VEX_LOG_DIR/*.log
$VEX_STRATUM_CONFIG_DIR/*.log
$VEX_NODE_APPDATA/logs/*/*.log
$VEX_WALLET_APPDATA/logs/*/*.log
$VEX_PEER_APPDATA/logs/*/*.log {
    daily
    rotate $VEX_LOG_RETENTION_DAYS
    missingok
    notifempty
    compress
    delaycompress
    copytruncate
    su root root
}
EOF
chmod 0644 /etc/logrotate.d/vexon-pool
echo "Installed /etc/logrotate.d/vexon-pool"

install_unit() {
  local name="$1"
  local content="$2"
  printf '%s\n' "$content" > "/etc/systemd/system/${name}"
  chmod 0644 "/etc/systemd/system/${name}"
  echo "Installed /etc/systemd/system/${name}"
}

install_unit vexon-pool-backup.service "[Unit]
Description=Vexon Pool production backup
After=mariadb.service

[Service]
Type=oneshot
WorkingDirectory=${repo_root}
ExecStart=/usr/bin/env bash ${repo_root}/scripts/run-backup.sh"

install_unit vexon-pool-backup.timer "[Unit]
Description=Run Vexon Pool production backup daily

[Timer]
OnCalendar=${VEX_BACKUP_ON_CALENDAR}
Persistent=true
RandomizedDelaySec=15m

[Install]
WantedBy=timers.target"

install_unit vexon-pool-monitor.service "[Unit]
Description=Vexon Pool health monitor
After=network-online.target mariadb.service nginx.service
Wants=network-online.target

[Service]
Type=oneshot
WorkingDirectory=${repo_root}
ExecStart=/usr/bin/env bash ${repo_root}/scripts/monitor-pool.sh"

install_unit vexon-pool-monitor.timer "[Unit]
Description=Run Vexon Pool health monitor

[Timer]
OnBootSec=2min
OnUnitActiveSec=${VEX_MONITOR_INTERVAL_SECONDS}
AccuracySec=30s
Persistent=true

[Install]
WantedBy=timers.target"

install_unit vexon-ssl-renew.service "[Unit]
Description=Vexon Pool SSL renewal check
After=network-online.target nginx.service
Wants=network-online.target

[Service]
Type=oneshot
WorkingDirectory=${repo_root}
ExecStart=/usr/bin/env bash ${repo_root}/scripts/ssl-renew-check.sh"

install_unit vexon-ssl-renew.timer "[Unit]
Description=Run Vexon Pool SSL renewal check

[Timer]
OnCalendar=${VEX_SSL_RENEW_ON_CALENDAR}
Persistent=true
RandomizedDelaySec=30m

[Install]
WantedBy=timers.target"

systemctl daemon-reload
systemctl enable --now vexon-pool-backup.timer vexon-ssl-renew.timer
if (( enable_now )); then
  systemctl enable --now vexon-pool-monitor.timer
else
  systemctl enable vexon-pool-monitor.timer
  echo "Enabled vexon-pool-monitor.timer but did not start it because --enable-now was not used."
fi

if systemctl list-unit-files certbot.timer --no-legend >/dev/null 2>&1; then
  systemctl enable --now certbot.timer >/dev/null 2>&1 || true
fi

echo
echo "Operations layer installed."
echo "Useful checks:"
echo "  systemctl list-timers 'vexon-*' --all"
echo "  journalctl -u vexon-pool-monitor.service -n 100 --no-pager"
echo "  sudo bash scripts/monitor-pool.sh"
echo "  sudo bash scripts/run-backup.sh"
echo "  sudo logrotate -d /etc/logrotate.d/vexon-pool"
