#!/usr/bin/env bash
# Build membershipd and install/enable/start it as a systemd user service.
# Idempotent: safe to re-run after a code change to rebuild and restart.
set -euo pipefail

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
UNIT="unibus-membershipd.service"
USER_UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"

cd "$APP_DIR"

echo "==> building membershipd (CGO_ENABLED=0)"
CGO_ENABLED=0 go build -o membershipd ./cmd/membershipd

echo "==> linking unit into $USER_UNIT_DIR"
mkdir -p "$USER_UNIT_DIR"
ln -sf "$APP_DIR/deploy/$UNIT" "$USER_UNIT_DIR/$UNIT"

echo "==> reloading systemd and (re)starting the service"
systemctl --user daemon-reload
systemctl --user enable --now "$UNIT"
# If the service was already running, enable --now does not restart it; do so to
# pick up the freshly built binary.
systemctl --user restart "$UNIT"

echo "==> status"
systemctl --user --no-pager status "$UNIT" || true

echo
echo "Health check:"
echo "  curl -fsS http://127.0.0.1:8470/healthz"
