#!/usr/bin/env bash
# Install /etc/systemd/system/whp-boot-orchestrator.service and enable it.
# Also generates a drop-in that wires boot_total_timeout_sec from settings.json
# into TimeoutStartSec. Idempotent.
set -euo pipefail

UNIT_NAME=whp-boot-orchestrator.service
DEST=/etc/systemd/system/${UNIT_NAME}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARBALL_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
SRC="${TARBALL_ROOT}/configs/whp-boot-orchestrator.service"

if [ ! -f "${SRC}" ]; then
    echo "FATAL: unit source not found at ${SRC}"; exit 1
fi
if [ -f "${DEST}" ] && cmp -s "${SRC}" "${DEST}"; then
    echo "${UNIT_NAME}: unchanged, skipping"
else
    install -m 0644 "${SRC}" "${DEST}"
    echo "${UNIT_NAME}: installed/updated"
fi

# Generate drop-in from settings.json so the admin-tuned boot_total_timeout_sec
# takes effect without editing the shipped unit file directly.
DROP_IN_DIR=/etc/systemd/system/${UNIT_NAME}.d
mkdir -p "${DROP_IN_DIR}"

TIMEOUT_VAL="600"
if [ -f /docker/whp/settings.json ] && command -v jq >/dev/null 2>&1; then
    TIMEOUT_VAL=$(jq -r '.boot_orchestrator.boot_total_timeout_sec // 600' /docker/whp/settings.json 2>/dev/null || echo "600")
    # Clamp: must be a positive integer
    if ! [[ "${TIMEOUT_VAL}" =~ ^[0-9]+$ ]] || [ "${TIMEOUT_VAL}" -lt 60 ]; then
        TIMEOUT_VAL="600"
    fi
fi

cat > "${DROP_IN_DIR}/timeout.conf" <<EOF
[Service]
TimeoutStartSec=${TIMEOUT_VAL}
EOF
chmod 0644 "${DROP_IN_DIR}/timeout.conf"
echo "${UNIT_NAME}: drop-in timeout=${TIMEOUT_VAL}s written to ${DROP_IN_DIR}/timeout.conf"

systemctl daemon-reload
systemctl enable "${UNIT_NAME}" >/dev/null 2>&1
echo "${UNIT_NAME}: enabled. Will run on next reboot."
