#!/usr/bin/env bash
# keepalive-heartbeat — keepalive heartbeat engine
#
# Runs a beat immediately at startup and then once every
# KEEPALIVE_INTERVAL seconds (default: 600 = 10 minutes, or 1200 when
# KEEPALIVE_CMD contains vmstat and KEEPALIVE_INTERVAL is not explicitly set),
# optionally split into KEEPALIVE_BEATS evenly spaced sub-beats.
#
# NOTE: this only generates activity inside the host. Whether that prevents
# VPS suspension depends on your provider's activity-detection policy.
#
# set -e is deliberately NOT used: the engine must survive individual command
# or network failures and log them as warnings. Only unbound variables are fatal.
set -u

SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd)" || SELF_DIR=""

keepalive_find_common() {
  local c
  for c in \
    "${KEEPALIVE_LIB_DIR:+${KEEPALIVE_LIB_DIR}/keepalive-common.sh}" \
    "${SELF_DIR:+${SELF_DIR}/../lib/keepalive-common.sh}" \
    "${HOME:+${HOME}/.local/lib/keepalive/keepalive-common.sh}" \
    "/usr/lib/keepalive/keepalive-common.sh"
  do
    if [ -n "$c" ] && [ -r "$c" ]; then
      printf '%s' "$c"
      return 0
    fi
  done
  return 1
}

COMMON_LIB="$(keepalive_find_common)" || {
  printf 'keepalive-heartbeat: cannot locate keepalive-common.sh\n' >&2
  exit 1
}
# shellcheck disable=SC1090
. "$COMMON_LIB"

keepalive_load_config
keepalive_validate_config || exit 1

STEP=$(( KEEPALIVE_INTERVAL / KEEPALIVE_BEATS ))
if [ "$STEP" -lt 1 ]; then
  STEP=1
fi

# Resolve built-in "workload" mode to keepalive-workload binary.
WORKLOAD_BIN=""
if [ "$KEEPALIVE_CMD" = "workload" ]; then
  WORKLOAD_BIN="$(keepalive_resolve_bin "keepalive-workload" "${SELF_DIR}/..")" || {
    printf 'keepalive-heartbeat: keepalive-workload not found. Run "keepalive install" or set KEEPALIVE_BIN_DIR.\n' >&2
    exit 1
  }
fi

# Ensure state directory and log file are writable before acquiring lock.
if ! mkdir -p "$KEEPALIVE_STATE_DIR" 2>/dev/null; then
  printf 'keepalive-heartbeat: cannot create state directory: %s\n' "$KEEPALIVE_STATE_DIR" >&2
  exit 1
fi
if [ ! -w "$KEEPALIVE_STATE_DIR" ]; then
  printf 'keepalive-heartbeat: state directory is not writable: %s\n' "$KEEPALIVE_STATE_DIR" >&2
  exit 1
fi
if [ -e "$KEEPALIVE_LOG_FILE" ] && [ ! -w "$KEEPALIVE_LOG_FILE" ]; then
  printf 'keepalive-heartbeat: log file is not writable: %s\n' "$KEEPALIVE_LOG_FILE" >&2
  exit 1
fi

# Acquire an exclusive lock to prevent duplicate instances on the same session.
LOCK_FILE="${KEEPALIVE_STATE_DIR}/keepalive-${KEEPALIVE_SESSION}.lock"
if command -v flock >/dev/null 2>&1; then
  exec 9>"$LOCK_FILE" || {
    printf 'keepalive-heartbeat: cannot open lock file: %s\n' "$LOCK_FILE" >&2
    exit 1
  }
  if ! flock -n 9; then
    printf 'keepalive-heartbeat: another instance is already running for session "%s" (lock: %s)\n' \
      "$KEEPALIVE_SESSION" "$LOCK_FILE" >&2
    exit 1
  fi
fi

SLEEP_PID=""
cleanup_and_exit() {
  local sig="${1:-TERM}"
  if [ -n "$SLEEP_PID" ]; then
    kill "$SLEEP_PID" 2>/dev/null || true
  fi
  keepalive_log INFO "shutdown: received ${sig}, exiting cleanly (pid=$$)"
  rm -f "$LOCK_FILE" 2>/dev/null || true
  exit 0
}
trap 'cleanup_and_exit SIGINT' INT
trap 'cleanup_and_exit SIGTERM' TERM
trap 'cleanup_and_exit SIGHUP' HUP

trim_output() {
  local out="$1"
  out="${out//$'\n'/ | }"
  out="${out//$'\r'/}"
  printf '%s' "${out:0:300}"
}

run_beat() {
  local out rc label
  if [ "$KEEPALIVE_CMD" = "workload" ]; then
    label="$WORKLOAD_BIN"
    if command -v timeout >/dev/null 2>&1; then
      out="$(timeout "$KEEPALIVE_CMD_TIMEOUT" "$WORKLOAD_BIN" 2>&1)"
      rc=$?
    else
      out="$("$WORKLOAD_BIN" 2>&1)"
      rc=$?
    fi
  else
    # Custom command mode: executed via bash -c (trusted operator configuration).
    label="$KEEPALIVE_CMD"
    if command -v timeout >/dev/null 2>&1; then
      out="$(timeout "$KEEPALIVE_CMD_TIMEOUT" bash -c "$KEEPALIVE_CMD" 2>&1)"
      rc=$?
    else
      out="$(bash -c "$KEEPALIVE_CMD" 2>&1)"
      rc=$?
    fi
  fi

  out="$(trim_output "$out")"
  if [ "$rc" -eq 0 ]; then
    keepalive_log INFO "heartbeat ok (exit 0): ${label}${out:+ :: $out}"
  elif [ "$rc" -eq 124 ]; then
    keepalive_log WARN "heartbeat TIMEOUT after ${KEEPALIVE_CMD_TIMEOUT}s: ${label}${out:+ :: $out}"
  else
    keepalive_log WARN "heartbeat FAILED (exit $rc): ${label}${out:+ :: $out}"
  fi
  return 0
}

run_network_beat() {
  local out rc gw safe_url
  if [ -n "$KEEPALIVE_PING_URL" ]; then
    safe_url="$(keepalive_redact_url "$KEEPALIVE_PING_URL")"
    if command -v curl >/dev/null 2>&1; then
      out="$(curl -fsS --connect-timeout 5 -m 10 -o /dev/null -w '%{http_code}' "$KEEPALIVE_PING_URL" 2>&1)"
      rc=$?
    elif command -v wget >/dev/null 2>&1; then
      out="$(wget -q -T 10 -O /dev/null "$KEEPALIVE_PING_URL" 2>&1 && printf 'ok')"
      rc=$?
    else
      out="neither curl nor wget is installed"
      rc=127
    fi
    out="$(trim_output "$out")"
    if [ "$rc" -eq 0 ]; then
      keepalive_log INFO "network heartbeat ok: ${safe_url} (${out:-ok})"
    else
      keepalive_log WARN "network heartbeat FAILED (exit $rc): ${safe_url}${out:+ :: $out}"
    fi
  fi

  if [ "$KEEPALIVE_PING_GATEWAY" = "1" ]; then
    gw="$(ip route show default 2>/dev/null | awk '/^default/ {print $3; exit}')"
    if [ -z "$gw" ]; then
      gw="$(route -n 2>/dev/null | awk '$1 == "0.0.0.0" {print $2; exit}')"
    fi
    if [ -z "$gw" ]; then
      keepalive_log WARN "gateway heartbeat skipped: no default gateway found"
    elif ! command -v ping >/dev/null 2>&1; then
      keepalive_log WARN "gateway heartbeat skipped: ping is not installed"
    elif command -v timeout >/dev/null 2>&1 && timeout 5 ping -c 1 -W 3 "$gw" >/dev/null 2>&1; then
      keepalive_log INFO "gateway heartbeat ok: ping ${gw}"
    elif ! command -v timeout >/dev/null 2>&1 && ping -c 1 "$gw" >/dev/null 2>&1; then
      keepalive_log INFO "gateway heartbeat ok: ping ${gw}"
    else
      keepalive_log WARN "gateway heartbeat FAILED: ping ${gw}"
    fi
  fi
  return 0
}

SAFE_PING_LOG="off"
if [ -n "$KEEPALIVE_PING_URL" ]; then
  SAFE_PING_LOG="$(keepalive_redact_url "$KEEPALIVE_PING_URL")"
fi

keepalive_log INFO "startup: version=${KEEPALIVE_VERSION} pid=$$ session=${KEEPALIVE_SESSION} interval=${KEEPALIVE_INTERVAL}s beats=${KEEPALIVE_BEATS}/interval (every ${STEP}s) command='${KEEPALIVE_CMD}' ping_url='${SAFE_PING_LOG}' ping_gateway=${KEEPALIVE_PING_GATEWAY} log=${KEEPALIVE_LOG_FILE}"

# Beat immediately once, then schedule against absolute deadlines using $SECONDS.
next_beat=$SECONDS
while :; do
  run_beat
  run_network_beat

  now=$SECONDS
  next_beat=$((next_beat + STEP))
  if [ "$now" -ge "$next_beat" ]; then
    next_beat=$((now + STEP))
  fi

  sleep "$((next_beat - now))" &
  SLEEP_PID=$!
  wait "$SLEEP_PID" 2>/dev/null || true
  SLEEP_PID=""
done
