#!/bin/bash
# Syncthing Setup Script for Timmy Fleet
# Run this on each VPS node to join the sync mesh

set -e

NODE_NAME="${1:-$(hostname)}"
HOME_DIR="${HOME:-/root}"
CONFIG_DIR="$HOME_DIR/.config/syncthing"
SHARED_DIR="$HOME_DIR/shared"

export HOME="$HOME_DIR"

echo "=== Syncthing Setup for $NODE_NAME ==="

# Install syncthing if not present
if ! command -v syncthing &> /dev/null; then
    echo "Installing Syncthing..."
    curl -sL "https://github.com/syncthing/syncthing/releases/download/v1.27.0/syncthing-linux-amd64-v1.27.0.tar.gz" | tar -xzf - -C /tmp/
    cp /tmp/syncthing-linux-amd64-v1.27.0/syncthing /usr/local/bin/
    chmod +x /usr/local/bin/syncthing
fi

# Create directories
mkdir -p "$CONFIG_DIR"
mkdir -p "$SHARED_DIR"

# Generate config if not exists
if [ ! -f "$CONFIG_DIR/config.xml" ]; then
    echo "Generating Syncthing config..."
    syncthing generate --config="$CONFIG_DIR"
fi

# Get device ID
DEVICE_ID=$(syncthing --config="$CONFIG_DIR" --device-id 2>/dev/null || grep -oP '(?<=<device id=")[^"]+' "$CONFIG_DIR/config.xml" | head -1)
echo "Device ID: $DEVICE_ID"

# Modify config: change folder path and bind GUI to localhost only
echo "Configuring Syncthing..."
sed -i 's|path="/root/Sync"|path="/root/shared"|g' "$CONFIG_DIR/config.xml"
sed -i 's|<address>127.0.0.1:8384</address>|<address>127.0.0.1:8384</address>|g' "$CONFIG_DIR/config.xml"
sed -i 's|<address>0.0.0.0:8384</address>|<address>127.0.0.1:8384</address>|g' "$CONFIG_DIR/config.xml"

# Create systemd service
cat > /etc/systemd/system/syncthing@root.service << 'EOF'
[Unit]
Description=Syncthing - Open Source Continuous File Synchronization for %i
Documentation=man:syncthing(1)
After=network.target

[Service]
User=%i
ExecStart=/usr/local/bin/syncthing -no-browser -no-restart -logflags=0
Restart=on-failure
RestartSec=5
SuccessExitStatus=3 4
RestartForceExitStatus=3 4
Environment="HOME=/root"

[Install]
WantedBy=multi-user.target
EOF

# Enable and start service
systemctl daemon-reload
systemctl enable syncthing@root.service
systemctl restart syncthing@root.service || systemctl start syncthing@root.service

echo ""
echo "=== Setup Complete ==="
echo "Node: $NODE_NAME"
echo "Device ID: $DEVICE_ID"
echo "Shared folder: $SHARED_DIR"
echo "Web UI: http://127.0.0.1:8384 (localhost only)"
echo ""
echo "To peer with another node, add their device ID via the web UI"
echo "or use: syncthing cli --config=$CONFIG_DIR config devices add --device-id=<ID>"
