#!/usr/bin/env bash
set -euo pipefail

# Check for root
if [ "$(id -u)" -ne 0 ]; then
  echo "Error: This script must be run as root or with sudo." >&2
  exit 1
fi

echo "==> Configuring Netbird systemd overrides..."

# 1. Ensure the systemd override directory exists
mkdir -p /etc/systemd/system/netbird.service.d

# 2. Write persistent environment variables
cat <<'EOF' > /etc/systemd/system/netbird.service.d/override.conf
[Service]
Environment="NB_ALLOW_SERVER_SSH=true"
Environment="NB_DISABLE_SSH_AUTH=true"
EOF

# 3. Reload systemd daemon to pick up the changes
systemctl daemon-reload

echo "==> Restarting Netbird service..."
systemctl restart netbird

echo "==> Bringing Netbird connection up with custom SSH flags..."
netbird down || true
netbird up --allow-server-ssh --disable-ssh-auth

echo "==> Done! Netbird is running and flags are locked across future updates."
