#!/usr/bin/env bash
# systemd_local_status — Estado + últimos logs de un servicio systemd local.
set -euo pipefail

systemd_local_status() {
    local name="$1"
    local log_lines="${2:-10}"

    if [[ -z "$name" ]]; then
        echo "systemd_local_status: se requiere name" >&2
        return 1
    fi

    local active sub pid enabled
    active=$(systemctl show -p ActiveState --value "${name}.service" 2>/dev/null || echo unknown)
    sub=$(systemctl show -p SubState --value "${name}.service" 2>/dev/null || echo unknown)
    pid=$(systemctl show -p MainPID --value "${name}.service" 2>/dev/null || echo 0)
    enabled=$(systemctl is-enabled "${name}.service" 2>/dev/null || echo disabled)

    # logs como array JSON
    local logs_json
    logs_json=$(journalctl -u "${name}.service" -n "$log_lines" --no-pager -o cat 2>/dev/null \
        | python3 -c 'import sys, json; print(json.dumps([l.rstrip() for l in sys.stdin if l.strip()]))' \
        2>/dev/null || echo "[]")

    printf '{"name":"%s","active":"%s","sub":"%s","enabled":"%s","pid":%s,"logs":%s}\n' \
        "$name" "$active" "$sub" "$enabled" "${pid:-0}" "$logs_json"
}
