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


shutdown_process() {
    process_name=$1
    echo "Stopping $process_name..."
    pids=$(ps | awk '/'"$process_name"'/ {print $1}')
    for pid in $pids; do
        if [ -n "$pid" ]; then
            kill "$pid"
            # Wait for the process to exit with a timeout
            count=0
            timeout=30 # 30 seconds timeout
            while kill -0 "$pid" 2>/dev/null; do
                sleep 1
                count=$((count + 1))
                if [ "$count" -ge "$timeout" ]; then
                    echo "Timeout reached, forcefully killing $process_name..."
                    kill -9 "$pid"
                    break
                fi
            done
        fi
    done
}


echo "Shutting down AMS..."
shutdown_process "amsbenchs"
shutdown_process "amsbenchr"
shutdown_process "ramsgate"
shutdown_process "amsd"

# updlsi hangs sometimes, manually shut it down now:
shutdown_process "udplsi"
