#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERVICE_NAME="anvil.service"
SERVICE_SRC="$SCRIPT_DIR/anvil.service"
SERVICE_DST="/etc/systemd/system/$SERVICE_NAME"

if ! command -v systemctl >/dev/null 2>&1; then
    echo "ERROR: systemctl is not available on this system"
    exit 1
fi

if [ "$EUID" -ne 0 ] && ! command -v sudo >/dev/null 2>&1; then
    echo "ERROR: sudo is required when not running as root"
    exit 1
fi

echo "=========================================="
echo "  RESTART ANVIL LOCAL"
echo "=========================================="

echo "Building debug static binary..."
"$SCRIPT_DIR/build_static.sh" --debug

echo "Syncing service file to $SERVICE_DST..."
if [ "$EUID" -eq 0 ]; then
    install -m 0644 "$SERVICE_SRC" "$SERVICE_DST"
    systemctl daemon-reload
    systemctl restart "$SERVICE_NAME"
    systemctl --no-pager --full status "$SERVICE_NAME" || true
else
    sudo install -m 0644 "$SERVICE_SRC" "$SERVICE_DST"
    sudo systemctl daemon-reload
    sudo systemctl restart "$SERVICE_NAME"
    sudo systemctl --no-pager --full status "$SERVICE_NAME" || true
fi

echo
echo "Anvil restarted."
echo "Context logs: /home/user/anvil/context.logs"
