#!/usr/bin/env bash
#
# onx-service-status — systemd servis durum sorgulama
#
# Stdin:  JSON {"unit":"httpd"}
# Stdout: JSON {
#           "unit":..., "active":bool, "enabled":bool,
#           "pid":int|null, "memory_mb":float, "uptime":str, "status_text":str
#         }
# Exit:   0=ok  1=invalid_input  3=execution_fail
#
# Sudoers: apache ALL=(root) NOPASSWD: /usr/local/onoxsoft/bin/onx-service-status
#
# Master Plan §5 — HestiaCP modeli

set -euo pipefail

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
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 JSON input from stdin
# ---------------------------------------------------------------------------
INPUT=$(cat)

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

[[ -z "$UNIT" ]] && die_input "unit alani gerekli"

# Whitelist: only lowercase letters, digits, hyphen, dot, @ (for systemd instances)
[[ "$UNIT" =~ ^[a-zA-Z0-9._@:-]{1,64}$ ]] || die_input "Gecersiz unit adi: ${UNIT}"

# Prevent path traversal
[[ "$UNIT" == *"/"* ]] && die_input "Gecersiz unit adi (slash iceremiyor)"

# ---------------------------------------------------------------------------
# Query systemd
# ---------------------------------------------------------------------------
# is-active: returns exit 0 if active, 3 if inactive/failed
ACTIVE_STR=$(systemctl is-active "${UNIT}" 2>/dev/null || true)
IS_ACTIVE=false
[[ "$ACTIVE_STR" == "active" ]] && IS_ACTIVE=true

ENABLED_STR=$(systemctl is-enabled "${UNIT}" 2>/dev/null || true)
IS_ENABLED=false
[[ "$ENABLED_STR" == "enabled" ]] && IS_ENABLED=true

# Detailed status output
STATUS_OUTPUT=$(systemctl status "${UNIT}" 2>/dev/null || true)

# Extract main PID
PID=null
if [[ "$IS_ACTIVE" == "true" ]]; then
  _PID=$(echo "$STATUS_OUTPUT" | grep -oP 'Main PID:\s*\K\d+' 2>/dev/null | head -1 || true)
  [[ -n "$_PID" ]] && PID=$_PID
fi

# Extract memory usage (MB) from cgroup
MEMORY_MB="0"
if [[ "$IS_ACTIVE" == "true" && "$PID" != "null" ]]; then
  _MEM_BYTES=$(cat "/sys/fs/cgroup/memory/system.slice/${UNIT}.service/memory.usage_in_bytes" 2>/dev/null \
    || systemctl show "${UNIT}" --property=MemoryCurrent 2>/dev/null | grep -oP '\d+' | head -1 \
    || echo "0")
  # Convert bytes to MB with 1 decimal
  if [[ "$_MEM_BYTES" =~ ^[0-9]+$ ]] && [[ "$_MEM_BYTES" -gt 0 ]]; then
    MEMORY_MB=$(awk "BEGIN {printf \"%.1f\", ${_MEM_BYTES}/1048576}")
  fi
fi

# Extract uptime from ActiveEnterTimestamp
UPTIME="—"
if [[ "$IS_ACTIVE" == "true" ]]; then
  _ENTER=$(systemctl show "${UNIT}" --property=ActiveEnterTimestamp 2>/dev/null \
    | grep -oP '=\K.+' | head -1 || true)
  if [[ -n "$_ENTER" && "$_ENTER" != "n/a" ]]; then
    _EPOCH=$(date -d "$_ENTER" +%s 2>/dev/null || true)
    _NOW=$(date +%s)
    if [[ -n "$_EPOCH" ]]; then
      _DIFF=$(( _NOW - _EPOCH ))
      if   [[ "$_DIFF" -lt 3600 ]];  then UPTIME="$(( _DIFF/60 )) dakika"
      elif [[ "$_DIFF" -lt 86400 ]]; then UPTIME="$(( _DIFF/3600 )) saat"
      elif [[ "$_DIFF" -lt 604800 ]];then UPTIME="$(( _DIFF/86400 )) gun"
      else UPTIME="$(( _DIFF/604800 )) hafta"
      fi
    fi
  fi
fi

# Short status line (first "Active:" line)
STATUS_TEXT=$(echo "$STATUS_OUTPUT" | grep -m1 '^\s*Active:' | sed 's/^\s*//' | cut -c1-120 || echo "${ACTIVE_STR}")
STATUS_TEXT_SAFE=$(json_str "$STATUS_TEXT")

# ---------------------------------------------------------------------------
# Output JSON
# ---------------------------------------------------------------------------
printf '{"unit":"%s","active":%s,"enabled":%s,"pid":%s,"memory_mb":%s,"uptime":"%s","status_text":"%s"}\n' \
  "$(json_str "$UNIT")" \
  "$IS_ACTIVE" \
  "$IS_ENABLED" \
  "$PID" \
  "$MEMORY_MB" \
  "$(json_str "$UPTIME")" \
  "$STATUS_TEXT_SAFE"

exit 0
