#!/bin/sh

set -eu

ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/../../.." && pwd)
SOURCE_SCRIPT="$ROOT_DIR/bin/restart_java_backend.sh"
TMP_DIR=$(mktemp -d)
TEST_ROOT="$TMP_DIR/app"
TEST_BIN_DIR="$TEST_ROOT/bin"
TEST_LOG_DIR="$TEST_ROOT/logs"
TEST_PORT=62481
EXTERNAL_PID=""

cleanup() {
    if [ -n "${EXTERNAL_PID:-}" ] && kill -0 "$EXTERNAL_PID" 2>/dev/null; then
        kill "$EXTERNAL_PID" 2>/dev/null || true
        wait "$EXTERNAL_PID" 2>/dev/null || true
    fi
    rm -rf "$TMP_DIR"
}

trap cleanup EXIT INT TERM

mkdir -p "$TEST_BIN_DIR" "$TEST_LOG_DIR"
cp "$SOURCE_SCRIPT" "$TEST_BIN_DIR/restart_java_backend.sh"
chmod +x "$TEST_BIN_DIR/restart_java_backend.sh"

python3 -m http.server "$TEST_PORT" --bind 127.0.0.1 > "$TMP_DIR/external.log" 2>&1 &
EXTERNAL_PID=$!

sleep 1

if ! kill -0 "$EXTERNAL_PID" 2>/dev/null; then
    echo "失败: 未能启动外部占口进程"
    exit 1
fi

python3 - "$TEST_BIN_DIR/restart_java_backend.sh" "$TEST_PORT" <<'PY'
from pathlib import Path
import sys

script_path = Path(sys.argv[1])
port = sys.argv[2]
content = script_path.read_text(encoding="utf-8")
content = content.replace("SERVER_PORT=62318", f"SERVER_PORT={port}")
script_path.write_text(content, encoding="utf-8")
PY

echo "[检查] stop 不能误杀未由脚本托管的占口进程"
sh "$TEST_BIN_DIR/restart_java_backend.sh" stop >/dev/null 2>&1 || true

if ! kill -0 "$EXTERNAL_PID" 2>/dev/null; then
    echo "失败: stop 误杀了未托管的外部进程"
    exit 1
fi

echo "通过"
