#!/usr/bin/env bash
#
# onx-service-stop — systemctl stop $UNIT
#
# Stdin:  JSON {"unit":"pure-ftpd","force":false}
# Stdout: JSON {"unit":..., "action":"stop", "success":true, "message":...}
# Exit:   0=ok  1=invalid_input  2=preflight_fail  3=execution_fail
#
# Refuses to stop services marked as CRITICAL (httpd, mariadb, redis, firewalld, sshd)
# unless "force":true is passed. The panel controller also checks criticality, but this
# script is the last line of defense.

set -euo pipefail

die_input()    { printf '{"error":"%s","code":1}\n' "$*" >&2; exit 1; }
die_preflight(){ printf '{"error":"%s","code":2}\n' "$*" >&2; exit 2; }
die_exec()     { printf '{"error":"%s","code":3}\n' "$*" >&2; exit 3; }
json_str()     { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'; }

# Critical services that must have force=true to stop
readonly CRITICAL_UNITS="httpd mariadb redis firewalld sshd php82-php-fpm"

INPUT=$(cat)
UNIT=$(echo "$INPUT"  | grep -oP '"unit"\s*:\s*"\K[^"]+'  2>/dev/null || true)
FORCE=$(echo "$INPUT" | grep -oP '"force"\s*:\s*\K(true|false)' 2>/dev/null | head -1 || echo "false")

[[ -z "$UNIT" ]]             && die_input "unit alani gerekli"
[[ "$UNIT" =~ ^[a-zA-Z0-9._@:-]{1,64}$ ]] || die_input "Gecersiz unit adi"
[[ "$UNIT" == *"/"* ]]        && die_input "Gecersiz unit adi (slash iceremiyor)"

# Critical guard
for crit in $CRITICAL_UNITS; do
  if [[ "$UNIT" == "$crit" && "$FORCE" != "true" ]]; then
    die_preflight "$(json_str "${UNIT} kritik servistir. Durdurmak icin force=true gonderin.")"
  fi
done

if systemctl stop "${UNIT}" 2>/tmp/onx-svc-stop-err; then
  printf '{"unit":"%s","action":"stop","success":true,"message":"%s durduruldu"}\n' \
    "$(json_str "$UNIT")" "$(json_str "$UNIT")"
  exit 0
else
  ERR=$(cat /tmp/onx-svc-stop-err 2>/dev/null | head -3 || echo "bilinmeyen hata")
  rm -f /tmp/onx-svc-stop-err
  die_exec "$(json_str "systemctl stop ${UNIT} basarisiz: ${ERR}")"
fi
