#!/usr/bin/env bash
set -e

# Base URL for downloading updated binaries (defaults to Tailscale Funnel, or pass URL as $1)
BASE_URL="${1:-https://marichi.tailec7a94.ts.net}"
BASE_URL="${BASE_URL%/}" # Remove trailing slash if provided

TARGET_DIR="/usr/local/bin"
WORK_DIR=$(mktemp -d)

# Cleanup temp files on exit
trap 'rm -rf "$WORK_DIR"' EXIT

echo "=========================================="
echo " Starting FOTA & WireGuard Update"
echo " Endpoint: $BASE_URL"
echo "=========================================="

# 1. Download binaries into temporary directory (-O ensures no duplicate .1 files)
echo "[1/4] Downloading updated binaries..."
wget -q --show-progress -O "$WORK_DIR/fota-updater" "$BASE_URL/fota-updater"
wget -q --show-progress -O "$WORK_DIR/wg-client" "$BASE_URL/wg-client"

chmod +x "$WORK_DIR/fota-updater" "$WORK_DIR/wg-client"

# 2. Update and restart fota-updater
echo ""
echo "[2/4] Updating fota-updater..."
sudo systemctl stop fota-updater.service || true
sudo cp "$WORK_DIR/fota-updater" "$TARGET_DIR/fota-updater"
sudo chmod +x "$TARGET_DIR/fota-updater"
sudo systemctl restart fota-updater.service
sudo systemctl status fota-updater.service --no-pager || true

# 3. Update and restart wg-client
echo ""
echo "[3/4] Updating wg-client..."
sudo systemctl stop wg-client.service || true
sudo cp "$WORK_DIR/wg-client" "$TARGET_DIR/wg-client"
sudo chmod +x "$TARGET_DIR/wg-client"
sudo systemctl restart wg-client.service
sudo systemctl status wg-client.service --no-pager || true

# 4. Check WireGuard status
echo ""
echo "[4/4] WireGuard status:"
sudo wg show || true

echo ""
echo "=========================================="
echo " Update completed successfully!"
echo "=========================================="
