#!/bin/bash

# Parse -p for target id (defaults to 8 if not provided)
# usage() {
#   echo "Usage: $0 [-p process_id]" >&2
#   exit 1
# }


kill_homepage_processes() {
  local homepage_path="$1"
  local process_id="$2"

  # Get all running app.py processes
  pgrep -f "app.py" | while read -r pid; do
    # Determine the port this process is listening on
    # cmd=$(ps -p "$pid" -o command=)
    # port=""
    # if [[ $cmd =~ --port[[:space:]]+([0-9]+) ]]; then
    #   port="${BASH_REMATCH[1]}"
    # fi

    # Fallback: try to infer port from socket listing
    if [[ -z "$port" ]]; then
      port=$(ss -ltnp 2>/dev/null | awk -v pid="$pid" '$0 ~ ("pid=" pid ",") {print $4}' | sed -E 's/.*:([0-9]+)$/\1/' | head -n 1)
    fi

    if [[ -z "$port" ]]; then
      echo "PID $pid: could not determine port; skipping"
      continue
    fi

    # Query the /process_id endpoint to retrieve the instance id
    instance_id=$(curl -sS --max-time 1 "http://127.0.0.1:$port/process_id" || true)

    if [[ "$instance_id" == "$process_id" ]]; then
      echo "Killing homepage Flask process with ID $instance_id, PID $pid on port $port..."
      kill -9 "$pid" || true
    else
      echo "Skipping PID $pid on port $port (instance_id=$instance_id)"
    fi
  done
}

kill_homepage_processes "environment_docker/webarena-homepage" 8


# target_id=""
# while getopts ":p:h" opt; do
#   case $opt in
#     p)
#       target_id="$OPTARG"
#       ;;
#     h)
#       usage
#       ;;
#     \?)
#       usage
#       ;;
#   esac
# done

# if [[ -z "$target_id" ]]; then
#   target_id=8
# fi

# temp_status_file=$(mktemp)
# # Generate status of all sites for the target id
# bash ./scripts/environments/check_websites.sh -p "$target_id" > "$temp_status_file"

# # Parse the status file and kill homepage-target_id sites that are UP
# while read -r site status _ url; do
#     # Expect lines like: "homepage-8   UP   URL: http://localhost:25878"
#     if [[ -z "$site" || -z "$status" || -z "$url" ]]; then
#         continue
#     fi

#     if [[ "$site" != "homepage-$target_id" ]]; then
#         continue
#     fi

#     if [[ "$status" != "UP" ]]; then
#         continue
#     fi

#     # Extract port from URL (e.g., http://localhost:25878)
#     port=${url##*:}

#     # Find PID listening on this port
#     pid=$(ss -ltnp 2>/dev/null | awk -v p=":$port" '$0 ~ p && $0 ~ /LISTEN/ { if (match($0, /pid=([0-9]+)/, a)) { print a[1]; exit } }')

#     if [[ -z "$pid" ]]; then
#         echo "No PID found listening on port $port for $site; skipping"
#         continue
#     fi

#     # Verify process_id via endpoint before killing
#     instance_id=$(curl -sS --max-time 1 "http://127.0.0.1:$port/process_id" || true)

#     if [[ "$instance_id" == "$target_id" ]]; then
#         echo "Killing $site on port $port (PID $pid)..."
#         kill -9 "$pid" || true
#     else
#         echo "Skipping $site on port $port (PID $pid): reported instance_id='$instance_id'"
#     fi

# done < "$temp_status_file"

# rm -f "$temp_status_file"