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

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

if [[ -f .env ]]; then
  set -a
  # shellcheck source=/dev/null
  source .env
  set +a
fi

VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_LOG_DIR="${VEX_LOG_DIR:-$VEX_POOL_ROOT/log}"
VEX_MONITOR_RESTART="${VEX_MONITOR_RESTART:-1}"
VEX_MONITOR_GRACE_SECONDS="${VEX_MONITOR_GRACE_SECONDS:-20}"
VEX_START_WALLET="${VEX_START_WALLET:-0}"

install -d -m 775 "$VEX_LOG_DIR"
log_file="${VEX_MONITOR_LOG:-$VEX_LOG_DIR/monitor.log}"
touch "$log_file"

log() {
  printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S %Z')" "$*" | tee -a "$log_file"
}

systemd_unit_exists() {
  local unit="$1"
  systemctl list-unit-files "$unit" --no-legend 2>/dev/null | awk '{print $1}' | grep -qx "$unit"
}

restart_stack() {
  local services=()
  local unit

  for unit in \
    vexon-node.service \
    vexon-peer.service \
    vexon-wallet.service \
    vexon-stratum.service \
    vexon-pool-main.service \
    vexon-pool-loop2.service \
    vexon-pool-blocks.service; do
    if systemd_unit_exists "$unit"; then
      if [[ "$unit" == "vexon-wallet.service" && "$VEX_START_WALLET" != "1" ]]; then
        continue
      fi
      services+=("$unit")
    fi
  done

  if (( ${#services[@]} == 0 )); then
    log "[FAIL] no Vexon systemd units are installed; run scripts/install-ops.sh first"
    return 1
  fi

  log "[FIX] restarting ${services[*]}"
  systemctl restart "${services[@]}"
}

tmp="$(mktemp /tmp/vexon-monitor.XXXXXX)"
trap 'rm -f "$tmp"' EXIT

log "running health check"
if bash scripts/health-check.sh >"$tmp" 2>&1; then
  log "[OK] health check passed"
  exit 0
fi

log "[FAIL] health check failed"
cat "$tmp" >> "$log_file"

if [[ "$VEX_MONITOR_RESTART" != "1" ]]; then
  log "[INFO] automatic restart disabled by VEX_MONITOR_RESTART=$VEX_MONITOR_RESTART"
  exit 1
fi

if [[ "$(id -u)" != "0" ]]; then
  log "[FAIL] automatic restart requires root"
  exit 1
fi

if ! command -v systemctl >/dev/null 2>&1; then
  log "[FAIL] systemctl is unavailable"
  exit 1
fi

if [[ -x scripts/repair-vex-coin.sh ]]; then
  log "[FIX] repairing VEX coin database row without starting screen Stratum"
  if ! bash scripts/repair-vex-coin.sh --no-restart >> "$log_file" 2>&1; then
    log "[WARN] VEX coin repair failed; continuing with service restart"
  fi
fi

restart_stack
sleep "$VEX_MONITOR_GRACE_SECONDS"

if bash scripts/health-check.sh >"$tmp" 2>&1; then
  log "[OK] health check recovered after restart"
  exit 0
fi

log "[FAIL] health check still failing after restart"
cat "$tmp" >> "$log_file"
exit 1
