#!/usr/bin/env bash
# systemd_local_install_unit — Instala un unit file en /etc/systemd/system y recarga systemd.
set -euo pipefail

systemd_local_install_unit() {
    local name="$1"
    local unit_content="$2"

    if [[ -z "$name" || -z "$unit_content" ]]; then
        echo "systemd_local_install_unit: se requieren name y unit_content" >&2
        return 1
    fi

    local unit_path="/etc/systemd/system/${name}.service"
    local tmp
    tmp="$(mktemp)"
    printf '%s' "$unit_content" > "$tmp"

    if ! sudo install -m 0644 -o root -g root "$tmp" "$unit_path"; then
        rm -f "$tmp"
        echo "systemd_local_install_unit: no se pudo instalar '$unit_path'" >&2
        return 1
    fi
    rm -f "$tmp"

    if ! sudo systemctl daemon-reload; then
        echo "systemd_local_install_unit: daemon-reload falló" >&2
        return 1
    fi

    printf '{"name":"%s","path":"%s","installed":true}\n' "$name" "$unit_path"
}
