#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_BINARY="$SCRIPT_DIR/didactyl_static_x86_64"
REMOTE_HOST="ubuntu@laantungir.net"
REMOTE_TARGETS=(
    "/home/simon/didactyl"
    "/home/didactyl/didactyl"
)
REMOTE_SERVICES=(
    "simon.service"
    "didactyl.service"
)

if ! command -v rsync >/dev/null 2>&1; then
    echo "ERROR: rsync is not installed or not in PATH"
    exit 1
fi

if ! command -v ssh >/dev/null 2>&1; then
    echo "ERROR: ssh is not installed or not in PATH"
    exit 1
fi

echo "Building static binary first..."
"$SCRIPT_DIR/build_static.sh"

if [ ! -f "$SOURCE_BINARY" ]; then
    echo "ERROR: Build completed but source binary not found: $SOURCE_BINARY"
    exit 1
fi

REMOTE_STAGE="/tmp/didactyl_static_x86_64"

echo "Uploading $SOURCE_BINARY to staging path $REMOTE_HOST:$REMOTE_STAGE"
rsync -avz --progress "$SOURCE_BINARY" "$REMOTE_HOST:$REMOTE_STAGE"

for target in "${REMOTE_TARGETS[@]}"; do
    echo "Installing staged binary to $target via sudo"
    ssh "$REMOTE_HOST" "sudo install -m 0755 '$REMOTE_STAGE' '$target'"
done

echo "Restarting services on $REMOTE_HOST: ${REMOTE_SERVICES[*]}"
ssh "$REMOTE_HOST" "sudo systemctl restart ${REMOTE_SERVICES[*]}"

echo "Cleaning up remote staging file $REMOTE_STAGE"
ssh "$REMOTE_HOST" "rm -f '$REMOTE_STAGE'"

echo "Deployment complete for all targets and services."