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

PROJECT_DIR="/home/long/project/蚊子"
STATE_DIR="$PROJECT_DIR/logs/e2e-automation"
PID_FILE="$STATE_DIR/runner.pid"
WATCHDOG_LOG="$STATE_DIR/watchdog.log"
RUNNER="$PROJECT_DIR/scripts/e2e_continuous_runner.sh"
CONTRACT_CHECK="$PROJECT_DIR/scripts/validate_test_contracts.sh"

mkdir -p "$STATE_DIR"
log(){ echo "[$(date '+%F %T')] [kick] $*" >> "$WATCHDOG_LOG"; }

if [ ! -x "$CONTRACT_CHECK" ]; then
  log "data-contract checker missing: $CONTRACT_CHECK"
  exit 2
fi

if ! SPRING_PROFILES_ACTIVE="${SPRING_PROFILES_ACTIVE:-e2e}" "$CONTRACT_CHECK" "$PROJECT_DIR" preflight >> "$WATCHDOG_LOG" 2>&1; then
  log "data-contract preflight failed; skip kick"
  exit 2
fi

# 允许周期性复跑：清理完成标记，触发新一轮回归
if [ -f "$STATE_DIR/done.flag" ]; then
  rm -f "$STATE_DIR/done.flag"
  log "removed done.flag for scheduled rerun"
fi

if [ -f "$PID_FILE" ]; then
  pid="$(cat "$PID_FILE" 2>/dev/null || true)"
  if [ -n "${pid:-}" ] && kill -0 "$pid" 2>/dev/null; then
    log "runner already running pid=$pid"
    exit 0
  fi
fi

nohup "$RUNNER" > "$STATE_DIR/nohup.out" 2>&1 &
new_pid=$!
echo "$new_pid" > "$PID_FILE"
log "runner kicked pid=$new_pid"
