#!/usr/bin/env bash
#
# onx-webserver-action — start/stop/restart/reload/enable/disable bir web server service.
#
# Input: {"driver":"...","service":"httpd|nginx|...","action":"start|stop|restart|reload|enable|disable"}
# Output: {"ok":true,"action":"X","service":"Y","running":bool}

set -uo pipefail
input="$(cat 2>/dev/null || echo '{}')"
driver="$(echo "$input" | jq -r '.driver // empty')"
service="$(echo "$input" | jq -r '.service // empty')"
action="$(echo "$input" | jq -r '.action // empty')"

[[ -z "$service" || -z "$action" ]] && { jq -nc '{ok:false,error:"service+action required"}' >&2; exit 1; }

case "$action" in
    start|stop|restart|reload|enable|disable)
        systemctl "$action" "$service" 2>&1
        rc=$?
        ;;
    *)
        jq -nc --arg a "$action" '{ok:false,error:"unknown action",action:$a}' >&2; exit 1
        ;;
esac

running="false"
systemctl is-active --quiet "$service" 2>/dev/null && running="true"

jq -nc \
    --arg driver "$driver" --arg service "$service" --arg action "$action" \
    --argjson running "$running" --argjson rc "$rc" \
    '{ok:($rc==0), driver:$driver, service:$service, action:$action, running:$running, rc:$rc}'
