#!/usr/bin/env bash
# Sky DeBaun Mar 2024

shutdown_process() {
    local process_name=$1
    # Print the main header for this process group
    echo "Shutting down '$process_name'..."

    local pids
    pids=$(pgrep -f "$process_name")

    if [ -z "$pids" ]; then
        # Indent the status message
        echo "  -> Not found."
        return
    fi

    # Loop through each found PID and handle it individually
    for pid in $pids; do
        if [ -n "$pid" ]; then
            echo "  -> Terminating PID: $pid"

            # Attempt graceful shutdown first
            kill "$pid"

            local count=0
            local timeout=30 # 30 seconds timeout
            while kill -0 "$pid" 2>/dev/null; do
                sleep 1
                count=$((count + 1))
                if [ "$count" -ge "$timeout" ]; then
                    echo "    -> Timed out. Forcefully killing PID: $pid"
                    kill -9 "$pid"
                    break
                fi
            done
            echo "  -> Stopped."
        fi
    done
}

echo "Shutting down AMS benchtest processes..."
shutdown_process "amsbenchs"
shutdown_process "amsbenchr"
shutdown_process "ramsgate"
shutdown_process "amsd"
shutdown_process "udplsi"

echo "Shutdown script finished."
