#!/bin/bash
set -euo pipefail
source "$(dirname "$0")/lib.sh"

log "Installing systemd units..."

for unit in direwolf linbpq pat; do
    template_install \
        "${ROOT}/configs/${unit}.service" \
        "/tmp/${unit}.service"
    sudo cp "/tmp/${unit}.service" "/etc/systemd/system/${unit}.service"
    rm -f "/tmp/${unit}.service"
done

sudo systemctl daemon-reload

DEFAULT_MODEM="${DEFAULT_MODEM:-graywolf}"

log "Enabling always-on services..."
sudo systemctl enable linbpq pat gpsd chrony

if [[ "$DEFAULT_MODEM" == "direwolf" ]]; then
    log "Default modem: Direwolf"
    sudo systemctl enable direwolf
    sudo systemctl disable graywolf 2>/dev/null || true
else
    log "Default modem: Graywolf (ensure graywolf package/service is already installed)"
    sudo systemctl enable graywolf 2>/dev/null || warn "graywolf.service not found — install Graywolf separately, then: sudo systemctl enable graywolf"
    sudo systemctl disable direwolf 2>/dev/null || true
fi

log "Services configured. Graywolf itself is not bundled in this installer — install from upstream if needed."
log "https://github.com/chrissnell/graywolf"
