#!/bin/sh
# deploy-agent — build mcp-agent and deploy to a node via SSH.
#
# Usage: script/deploy-agent <node> [arch]
#
# Builds the mcp-agent binary for the target architecture, copies it
# to /srv/mcp/mcp-agent on the node, and restarts the systemd service.
#
# Arguments:
#   node   SSH hostname (e.g., rift, hyperborea)
#   arch   GOARCH value (default: amd64)
#
# Examples:
#   script/deploy-agent rift
#   script/deploy-agent hyperborea arm64

set -eu

NODE="${1:?usage: deploy-agent <node> [arch]}"
ARCH="${2:-amd64}"
REMOTE_PATH="/srv/mcp/mcp-agent"
SERVICE="mcp-agent"

VERSION="$(git describe --tags --always --dirty 2>/dev/null || echo unknown)"
BINARY="mcp-agent.${NODE}"

printf "building mcp-agent %s for %s (%s)\n" "$VERSION" "$NODE" "$ARCH"
CGO_ENABLED=0 GOARCH="$ARCH" go build \
    -trimpath \
    -ldflags="-s -w -X main.version=${VERSION}" \
    -o "$BINARY" \
    ./cmd/mcp-agent

printf "deploying to %s:%s\n" "$NODE" "$REMOTE_PATH"
scp "$BINARY" "${NODE}:/tmp/mcp-agent.new"
ssh "$NODE" "doas sh -c 'systemctl stop ${SERVICE} && cp /tmp/mcp-agent.new ${REMOTE_PATH} && systemctl start ${SERVICE}' && rm /tmp/mcp-agent.new"

printf "verifying %s on %s\n" "$SERVICE" "$NODE"
ssh "$NODE" "systemctl is-active ${SERVICE}"

rm -f "$BINARY"
printf "done: %s deployed to %s\n" "$VERSION" "$NODE"
