#!/usr/bin/env bash
#
# onx-process-kill — Güvenli `kill -SIG <pid>` çağrısı.
#
# Stdin:  JSON {"pid":12345,"signal":15}
# Stdout: JSON {"killed":true,"pid":12345,"signal":15,"comm":"php-fpm"}
# Exit:   0=ok  1=invalid_input  2=preflight_fail (korumalı/yok)  3=execution_fail
#
# Güvenlik katmanları:
#   1. PID < 100 → init/systemd alanı, reddet
#   2. /proc/<pid>/comm whitelist → systemd/sshd/init/php-fpm/apache/nginx korunur
#   3. Sinyal whitelist → sadece 1(HUP), 15(TERM), 9(KILL)
#
# Sudoers: apache ALL=(root) NOPASSWD: /usr/local/onoxsoft/bin/onx-process-kill
#
# Master Plan §5 — HestiaCP modeli

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck disable=SC1091
source "${SCRIPT_DIR}/_lib/common.sh"

# ─── Parse stdin ─────────────────────────────────────────────────────────────
onx_json_input

PID=$(onx_json_field 'pid' '')
SIGNAL=$(onx_json_field 'signal' '15')

# Validate PID
[[ -n "$PID" ]] || onx_die 1 "pid required"
[[ "$PID" =~ ^[0-9]+$ ]] || onx_die 1 "pid must be integer"

# Layer 1: PID < 100 → init/systemd reserve range
(( PID >= 100 )) || onx_die 1 "PID < 100 is protected (init/systemd range)"

# Validate signal (whitelist)
case "$SIGNAL" in
    1|15|9) ;;
    HUP)  SIGNAL=1 ;;
    TERM) SIGNAL=15 ;;
    KILL) SIGNAL=9 ;;
    *) onx_die 1 "invalid signal: must be 1(HUP), 15(TERM), or 9(KILL)" ;;
esac

# Preflight: process exists?
if [[ ! -r "/proc/${PID}/comm" ]]; then
    # Sistem dışı OS — fallback: ps -p
    if ! ps -p "$PID" >/dev/null 2>&1; then
        onx_die 2 "process ${PID} not found"
    fi
    COMM=$(ps -p "$PID" -o comm= 2>/dev/null | tr -d '[:space:]')
else
    COMM=$(tr -d '[:space:]' < "/proc/${PID}/comm")
fi

# Layer 2: critical comm whitelist
case "$COMM" in
    systemd|init|kernel|kthreadd|ksoftirqd*|sshd|systemd-*|php-fpm|httpd|apache|apache2|nginx)
        onx_die 2 "protected process '${COMM}' (PID ${PID}) — kill blocked"
        ;;
esac

require_cmd kill

# ─── Send signal ─────────────────────────────────────────────────────────────
if kill "-${SIGNAL}" "$PID" 2>/dev/null; then
    onx_log "process-kill pid=${PID} signal=${SIGNAL} comm=${COMM} → ok"
    jq -n \
        --argjson pid "$PID" \
        --argjson signal "$SIGNAL" \
        --arg comm "$COMM" \
        '{killed: true, pid: $pid, signal: $signal, comm: $comm}'
    exit 0
fi

onx_die 3 "kill ${PID} failed (errno=$?); permission denied or process gone"
