#!/bin/bash
# Generated by Gemini 2.5.

CHECK_INTERVAL=1

# Free up ports in the given range.
free_ports() {
    local START_PORT=$1
    local END_PORT=$2

    while true; do
        ports_in_use=()
        pids_to_kill=()

        for port in $(seq $START_PORT $END_PORT); do
            pid=$(sudo lsof -Pni udp:"${port}" | awk 'NR>1 {print $2}' | head -n 1)

            if [[ -n "$pid" ]]; then
                ports_in_use+=("$port")
                if ! [[ " ${pids_to_kill[@]} " =~ " ${pid} " ]]; then
                    pids_to_kill+=("$pid")
                fi
            fi
        done

        if [ ${#ports_in_use[@]} -eq 0 ]; then
            break
        else
            killed_something=false
            for pid_to_kill in "${pids_to_kill[@]}"; do
                sudo kill "${pid_to_kill}" &> /dev/null
                sleep 0.5

                if ps -p "${pid_to_kill}" > /dev/null; then
                    sudo kill -9 "${pid_to_kill}" &> /dev/null
                    if [[ $? -eq 0 ]]; then
                        killed_something=true
                    fi
                else
                    killed_something=true
                fi
            done
            sleep ${CHECK_INTERVAL}
        fi
    done
}

free_ports 31850 31859

# If no `cli` passed as argument, free up server port space.
if [[ $1 != "cli" ]]; then
    free_ports 31890 31899
fi

echo "Freed ports."
