#!/usr/bin/env bash
# Build mediator for linux/amd64 and push it to the server.
# Run from your machine (Git Bash on Windows works):
#
#   ./deploy/deploy.sh [host]      default host: himalia
#
# Requires the one-time server setup (setup-server.sh) to have been run.
# Asks for the ssh password once; the binary is streamed over that same
# connection, swapped in atomically, and the service restarted.
set -euo pipefail

HOST="${1:-himalia}"
APP_DIR=/opt/mediator
cd "$(dirname "$0")/.."

echo "Building linux/amd64 binary..."
mkdir -p dist
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 \
    go build -trimpath -ldflags "-s -w" -o dist/mediator-linux-amd64 .

echo "Uploading to $HOST and restarting mediator..."
ssh "$HOST" "set -e
    cat > $APP_DIR/mediator.new
    chmod 755 $APP_DIR/mediator.new
    mv -f $APP_DIR/mediator.new $APP_DIR/mediator
    sudo systemctl restart mediator
    sleep 1
    systemctl is-active mediator
" < dist/mediator-linux-amd64

echo "Deployed $(git rev-parse --short HEAD) to $HOST."
