#!/usr/bin/env bash
# args_json: {"type":"object","required":["pid"],"properties":{"pid":{"type":"string","description":"Process PID"},"signal":{"type":"string","description":"Signal name: TERM (default) or KILL"}}}
# ollie:prompt
# ## process_signal
#
# Send a signal to a detached background process.
#
# ```
# process_signal(pid="12345", signal="TERM")
# ```
# ollie:end

set -euo pipefail

source "$(dirname "$0")/_lib/args.sh"

pid=$(arg_require "pid")
signal=$(arg_get "signal" "TERM")
session="${OLLIE_SESSION_ID:?OLLIE_SESSION_ID not set}"

# Find agent (use first agent in session)
agent=$(ollie-9p ls "session/$session/agent" 2>/dev/null | grep -v '^new$' | head -1)
[ -z "$agent" ] && { echo "error: no agent in session" >&2; exit 1; }

proc_path="session/$session/agent/$agent/proc/$pid"

case "$signal" in
    TERM|KILL)
        # Remove the proc file to signal termination
        ollie-9p rm "$proc_path" 2>/dev/null && \
            echo "Signal $signal sent to PID $pid" || \
            { echo "Failed to signal PID $pid (process may have already exited)" >&2; exit 1; }
        ;;
    *)
        echo "error: unsupported signal: $signal (use TERM or KILL)" >&2
        exit 1
        ;;
esac
