#!/usr/bin/env bash
#
# onx-service-reload — systemctl reload $UNIT (GRACEFUL — no port drop)
#
# v86.5 — service-restart yerine bunu kullan ki Apache/Nginx/OLS gibi
# servisler RELOAD ile config yeniden okusun, port hiç release etmesin.
# Restart = stop + start; reload = SIGHUP. Migration loop sonu reload için kritik.
#
# Stdin:  JSON {"unit":"httpd"}
# Stdout: JSON {"unit":..., "action":"reload", "success":true, "message":...}
# Exit:   0=ok  1=invalid_input  3=execution_fail

set -euo pipefail

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

# ---------------------------------------------------------------------------
# Parse stdin
# ---------------------------------------------------------------------------
INPUT=$(cat)
UNIT=$(echo "$INPUT" | grep -oP '"unit"\s*:\s*"\K[^"]+' 2>/dev/null || true)

[[ -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)"

# ---------------------------------------------------------------------------
# Execute — reload (graceful)
# ---------------------------------------------------------------------------
# `systemctl reload-or-restart` reload destekleyen unit'lerde reload, desteklemeyenlerde
# (rare) restart yapar. Apache, Nginx, OLS hepsi reload destekler → port hep bound.
if systemctl reload-or-restart "${UNIT}" 2>/tmp/onx-svc-reload-err; then
  MSG="$(json_str "${UNIT} graceful reload edildi")"
  printf '{"unit":"%s","action":"reload","success":true,"message":"%s"}\n' \
    "$(json_str "$UNIT")" "$MSG"
  exit 0
else
  ERR=$(cat /tmp/onx-svc-reload-err 2>/dev/null | head -3 || echo "bilinmeyen hata")
  rm -f /tmp/onx-svc-reload-err
  die_exec "$(json_str "systemctl reload-or-restart ${UNIT} basarisiz: ${ERR}")"
fi
