#!/bin/bash
# Build (if needed) and install mcpctl RPM locally
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

RPM_FILE=$(ls dist/mcpctl-*.rpm 2>/dev/null | head -1)

# Build if no RPM exists or if source is newer than the RPM
if [[ -z "$RPM_FILE" ]] || [[ $(find src/ -name '*.ts' -newer "$RPM_FILE" 2>/dev/null | head -1) ]]; then
    echo "==> Building RPM..."
    bash scripts/build-rpm.sh
    RPM_FILE=$(ls dist/mcpctl-*.rpm 2>/dev/null | head -1)
else
    echo "==> RPM is up to date: $RPM_FILE"
fi

echo "==> Installing $RPM_FILE..."
sudo rpm -Uvh --force "$RPM_FILE"

echo "==> Reloading systemd user units..."
systemctl --user daemon-reload

echo "==> Done!"
echo "    Enable mcplocal: systemctl --user enable --now mcplocal"
