#!/usr/bin/env bash
# ==============================================================================
# VPSGauge — Open-Source Reproducible VPS Benchmark Harness (v1.0.0)
# https://vpsgauge.com/methodology
#
# Measures:
#   1. Sysbench CPU Single-Core (events/sec, 30s, max-prime=20000)
#   2. Sysbench CPU Multi-Core (events/sec, all vCPUs, 30s) + CPU Steal %
#   3. Sysbench Memory Bandwidth (MiB/sec, 1M block, 10G total)
#   4. fio 4K Random Read / Write / 70-30 Mixed IOPS (direct=1, iodepth=64)
#   5. Network Throughput (iperf3 if server provided, or HTTP fallback)
#
# Emits standardized JSON ready to import into src/data/benchmarks.json.
#
# Usage:
#   curl -fsSL https://vpsgauge.com/scripts/vps-bench.sh | bash -s -- \
#     --plan-id hetzner-cx22 --provider hetzner --region eu-fsn1
# ==============================================================================

set -euo pipefail

HARNESS_VERSION="1.0.0"
PLAN_ID="custom-vps"
PROVIDER="unknown"
REGION="unknown"
IPERF_HOST=""
IPERF_PORT="5201"
OUTPUT_FILE=""
INSTALL_DEPS=false
DURATION_CPU=30
DURATION_FIO=30
FIO_SIZE="1G"
WORKDIR=""

usage() {
  cat <<'EOF'
VPSGauge Reproducible Benchmark Harness v1.0.0

Options:
  --plan-id <id>        Catalog plan ID (e.g. hetzner-cx22, do-basic-4gb)
  --provider <slug>     Provider slug (e.g. hetzner, digitalocean, vultr)
  --region <code >      Datacenter region code (e.g. eu-fsn1, us-nyc1)
  --iperf-host <host>   Optional iperf3 server hostname for network test
  --iperf-port <port>   Optional iperf3 port (default: 5201)
  --output <path>       Write JSON result to file (also prints to stdout)
  --install-deps        Attempt apt/dnf/apk install of sysbench, fio, iperf3, jq
  --quick               Shorten CPU & fio durations to 10s (for sanity checks only)
  -h, --help            Show this help message
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --plan-id)      PLAN_ID="$2"; shift 2 ;;
    --provider)     PROVIDER="$2"; shift 2 ;;
    --region)       REGION="$2"; shift 2 ;;
    --iperf-host)   IPERF_HOST="$2"; shift 2 ;;
    --iperf-port)   IPERF_PORT="$2"; shift 2 ;;
    --output)       OUTPUT_FILE="$2"; shift 2 ;;
    --install-deps) INSTALL_DEPS=true; shift ;;
    --quick)        DURATION_CPU=10; DURATION_FIO=10; FIO_SIZE="512M"; shift ;;
    -h|--help)      usage; exit 0 ;;
    *)              echo "Unknown option: $1" >&2; usage; exit 1 ;;
  esac
done

log() {
  echo "[vpsgauge] $*" >&2
}

cleanup() {
  if [[ -n "${WORKDIR}" && -d "${WORKDIR}" ]]; then
    rm -rf "${WORKDIR}"
  fi
}
trap cleanup EXIT

install_missing_deps() {
  local pkgs=(sysbench fio iperf3 jq curl bc)
  if command -v apt-get >/dev/null 2>&1; then
    log "Installing dependencies via apt-get..."
    DEBIAN_FRONTEND=noninteractive apt-get update -qq >&2
    DEBIAN_FRONTEND=noninteractive apt-get install -y -qq "${pkgs[@]}" >&2
  elif command -v dnf >/dev/null 2>&1; then
    log "Installing dependencies via dnf..."
    dnf install -y -q "${pkgs[@]}" >&2
  elif command -v apk >/dev/null 2>&1; then
    log "Installing dependencies via apk..."
    apk add --no-cache "${pkgs[@]}" >&2
  else
    log "ERROR: Unsupported package manager. Please install: ${pkgs[*]}"
    exit 1
  fi
}

check_deps() {
  local missing=()
  for cmd in sysbench fio jq awk bc; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
      missing+=("$cmd")
    fi
  done
  if [[ ${#missing[@]} -gt 0 ]]; then
    if [[ "$INSTALL_DEPS" == true ]]; then
      install_missing_deps
    else
      log "ERROR: Missing required tools: ${missing[*]}"
      log "Re-run with --install-deps or install them manually (apt install -y sysbench fio iperf3 jq bc curl)."
      exit 1
    fi
  fi
}

read_cpu_stat() {
  # Returns: total_ticks steal_ticks
  awk '/^cpu / {
    total = 0;
    for (i = 2; i <= NF; i++) total += $i;
    steal = ($9 != "" ? $9 : 0);
    printf "%s %s\n", total, steal;
  }' /proc/stat
}

check_deps

WORKDIR="$(mktemp -d /tmp/vpsgauge.XXXXXX)"
RUN_DATE_UTC="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"

# --- 1. Host Metadata ---
CPU_MODEL="$(awk -F: '/model name/ {gsub(/^[ \t]+/, "", $2); print $2; exit}' /proc/cpuinfo 2>/dev/null || true)"
if [[ -z "$CPU_MODEL" ]]; then
  CPU_MODEL="$(lscpu 2>/dev/null | awk -F: '/Model name/ {gsub(/^[ \t]+/, "", $2); print $2; exit}' || echo "Unknown CPU")"
fi
VCPU_COUNT="$(nproc 2>/dev/null || echo 1)"
RAM_MB="$(awk '/MemTotal/ {printf "%d", $2 / 1024}' /proc/meminfo 2>/dev/null || echo 0)"
VIRT_TYPE="$(systemd-detect-virt 2>/dev/null || echo "unknown")"
KERNEL_VER="$(uname -r)"

log "Host: ${CPU_MODEL} (${VCPU_COUNT} vCPU, ${RAM_MB} MB RAM, virt=${VIRT_TYPE})"

# --- 2. Sysbench CPU Single-Core ---
log "Running Sysbench CPU 1-thread (${DURATION_CPU}s)..."
SB_1T_OUT="$(sysbench cpu --threads=1 --time="${DURATION_CPU}" --cpu-max-prime=20000 run)"
SB_1T_EPS="$(echo "$SB_1T_OUT" | awk '/events per second:/ {print $4}')"
SB_1T_EPS="${SB_1T_EPS:-0}"

# --- 3. Sysbench CPU Multi-Core + CPU Steal Sampling ---
log "Running Sysbench CPU ${VCPU_COUNT}-thread (${DURATION_CPU}s) + sampling CPU steal..."
read -r CPU_TOT_BEFORE CPU_STEAL_BEFORE < <(read_cpu_stat)
SB_MT_OUT="$(sysbench cpu --threads="${VCPU_COUNT}" --time="${DURATION_CPU}" --cpu-max-prime=20000 run)"
read -r CPU_TOT_AFTER CPU_STEAL_AFTER < <(read_cpu_stat)

SB_MT_EPS="$(echo "$SB_MT_OUT" | awk '/events per second:/ {print $4}')"
SB_MT_EPS="${SB_MT_EPS:-0}"

DELTA_TOT=$((CPU_TOT_AFTER - CPU_TOT_BEFORE))
DELTA_STEAL=$((CPU_STEAL_AFTER - CPU_STEAL_BEFORE))
if [[ "$DELTA_TOT" -gt 0 ]]; then
  CPU_STEAL_PCT="$(awk -v s="$DELTA_STEAL" -v t="$DELTA_TOT" 'BEGIN {printf "%.2f", (s / t) * 100}')"
else
  CPU_STEAL_PCT="0.00"
fi

# --- 4. Sysbench Memory Bandwidth ---
log "Running Sysbench Memory Bandwidth (1M block, 10G total)..."
SB_MEM_OUT="$(sysbench memory --memory-block-size=1M --memory-total-size=10G --threads=1 run)"
SB_MEM_MIBS="$(echo "$SB_MEM_OUT" | awk -F'[()]' '/MiB\/sec/ {gsub(/[^0-9.]/, "", $2); print $2; exit}')"
SB_MEM_MIBS="${SB_MEM_MIBS:-0}"

# --- 5. fio 4K Random Disk IOPS (direct=1, iodepth=64) ---
FIO_FILE="${WORKDIR}/fio-bench.dat"
FIO_ENGINE="libaio"
if ! fio --enghelp 2>/dev/null | grep -q "libaio"; then
  FIO_ENGINE="psync"
fi

log "Running fio 4K random read (${DURATION_FIO}s, engine=${FIO_ENGINE})..."
FIO_READ_JSON="$(fio --name=randread --filename="${FIO_FILE}" --size="${FIO_SIZE}" \
  --rw=randread --bs=4k --direct=1 --iodepth=64 --ioengine="${FIO_ENGINE}" \
  --runtime="${DURATION_FIO}" --time_based --numjobs=1 --group_reporting --output-format=json)"
FIO_READ_IOPS="$(echo "$FIO_READ_JSON" | jq -r '.jobs[0].read.iops | floor')"

log "Running fio 4K random write (${DURATION_FIO}s)..."
FIO_WRITE_JSON="$(fio --name=randwrite --filename="${FIO_FILE}" --size="${FIO_SIZE}" \
  --rw=randwrite --bs=4k --direct=1 --iodepth=64 --ioengine="${FIO_ENGINE}" \
  --runtime="${DURATION_FIO}" --time_based --numjobs=1 --group_reporting --output-format=json)"
FIO_WRITE_IOPS="$(echo "$FIO_WRITE_JSON" | jq -r '.jobs[0].write.iops | floor')"

log "Running fio 4K 70/30 mixed random (${DURATION_FIO}s)..."
FIO_MIX_JSON="$(fio --name=randrw --filename="${FIO_FILE}" --size="${FIO_SIZE}" \
  --rw=randrw --rwmixread=70 --bs=4k --direct=1 --iodepth=64 --ioengine="${FIO_ENGINE}" \
  --runtime="${DURATION_FIO}" --time_based --numjobs=1 --group_reporting --output-format=json)"
FIO_MIX_IOPS="$(echo "$FIO_MIX_JSON" | jq -r '(.jobs[0].read.iops + .jobs[0].write.iops) | floor')"

rm -f "${FIO_FILE}"

# --- 6. Network Throughput (iperf3 if configured, otherwise 0) ---
NET_DOWN_MBPS="0"
NET_UP_MBPS="0"

if [[ -n "$IPERF_HOST" ]] && command -v iperf3 >/dev/null 2>&1; then
  log "Running iperf3 upload test against ${IPERF_HOST}:${IPERF_PORT}..."
  if IPERF_UP_JSON="$(iperf3 -c "${IPERF_HOST}" -p "${IPERF_PORT}" -t 10 -P 4 -J 2>/dev/null)"; then
    NET_UP_MBPS="$(echo "$IPERF_UP_JSON" | jq -r '((.end.sum_sent.bits_per_second // 0) / 1000000) | floor')"
  fi
  log "Running iperf3 download test against ${IPERF_HOST}:${IPERF_PORT}..."
  if IPERF_DOWN_JSON="$(iperf3 -c "${IPERF_HOST}" -p "${IPERF_PORT}" -t 10 -P 4 -R -J 2>/dev/null)"; then
    NET_DOWN_MBPS="$(echo "$IPERF_DOWN_JSON" | jq -r '((.end.sum_received.bits_per_second // 0) / 1000000) | floor')"
  fi
else
  log "Skipping iperf3 (pass --iperf-host <host> to record bidirectional Mbps)."
fi

# --- 7. Emit Standardized JSON ---
RESULT_JSON="$(jq -n \
  --arg planId "$PLAN_ID" \
  --arg provider "$PROVIDER" \
  --arg region "$REGION" \
  --arg runDateUtc "$RUN_DATE_UTC" \
  --arg harnessVersion "$HARNESS_VERSION" \
  --arg cpuModel "$CPU_MODEL" \
  --argjson vcpuDetected "$VCPU_COUNT" \
  --argjson ramMbDetected "$RAM_MB" \
  --arg virtualization "$VIRT_TYPE" \
  --arg kernel "$KERNEL_VER" \
  --argjson sysbenchCpu1T "$SB_1T_EPS" \
  --argjson sysbenchCpuMT "$SB_MT_EPS" \
  --argjson sysbenchMemMiBs "$SB_MEM_MIBS" \
  --argjson fio4kRandReadIops "$FIO_READ_IOPS" \
  --argjson fio4kRandWriteIops "$FIO_WRITE_IOPS" \
  --argjson fio4kMixedIops "$FIO_MIX_IOPS" \
  --argjson networkDownMbps "$NET_DOWN_MBPS" \
  --argjson networkUpMbps "$NET_UP_MBPS" \
  --argjson cpuStealPct "$CPU_STEAL_PCT" \
  '{
    planId: $planId,
    provider: $provider,
    region: $region,
    runDateUtc: $runDateUtc,
    harnessVersion: $harnessVersion,
    hostInfo: {
      cpuModel: $cpuModel,
      vcpuDetected: $vcpuDetected,
      ramMbDetected: $ramMbDetected,
      virtualization: $virtualization,
      kernel: $kernel
    },
    metrics: {
      sysbenchCpu1T: $sysbenchCpu1T,
      sysbenchCpuMT: $sysbenchCpuMT,
      sysbenchMemMiBs: $sysbenchMemMiBs,
      fio4kRandReadIops: $fio4kRandReadIops,
      fio4kRandWriteIops: $fio4kRandWriteIops,
      fio4kMixedIops: $fio4kMixedIops,
      networkDownMbps: $networkDownMbps,
      networkUpMbps: $networkUpMbps,
      cpuStealPct: $cpuStealPct
    }
  }')"

if [[ -n "$OUTPUT_FILE" ]]; then
  echo "$RESULT_JSON" > "$OUTPUT_FILE"
  log "Saved benchmark JSON to ${OUTPUT_FILE}"
fi

echo "$RESULT_JSON"
