#!/bin/bash
# Sync configuration files from live server to ISO build
#
# Usage: ./sync-from-live.sh [target-host]
#
# This script captures system configuration from the live development
# server and saves it to the image-recipe/configs/ directory for
# inclusion in future ISO builds.

set -e

# Configuration
TARGET_HOST="${1:-archipelago@192.168.1.228}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$SCRIPT_DIR/configs"

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  Syncing Configurations from Live Server                      ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo "Target: $TARGET_HOST"
echo "Output: $CONFIG_DIR"
echo ""

# Ensure configs directory exists
mkdir -p "$CONFIG_DIR"

# Sync systemd service
echo "📋 Capturing systemd service..."
ssh "$TARGET_HOST" 'sudo cat /etc/systemd/system/archipelago.service' > "$CONFIG_DIR/archipelago.service"
echo "   ✅ Saved to configs/archipelago.service"

# Sync nginx configuration
echo "📋 Capturing nginx configuration..."
ssh "$TARGET_HOST" 'sudo cat /etc/nginx/sites-available/archipelago' > "$CONFIG_DIR/nginx-archipelago.conf"
echo "   ✅ Saved to configs/nginx-archipelago.conf"

# Sync logrotate if it exists
if ssh "$TARGET_HOST" 'sudo test -f /etc/logrotate.d/archipelago'; then
    echo "📋 Capturing logrotate configuration..."
    ssh "$TARGET_HOST" 'sudo cat /etc/logrotate.d/archipelago' > "$CONFIG_DIR/logrotate.conf"
    echo "   ✅ Saved to configs/logrotate.conf"
fi

# Check for custom scripts
echo ""
echo "📋 Checking for custom scripts..."
if ssh "$TARGET_HOST" 'sudo test -d /opt/archipelago/scripts'; then
    SCRIPT_COUNT=$(ssh "$TARGET_HOST" 'sudo ls /opt/archipelago/scripts/ 2>/dev/null | wc -l' | tr -d ' ')
    if [ "$SCRIPT_COUNT" -gt 0 ]; then
        echo "   ⚠️  Found $SCRIPT_COUNT script(s) in /opt/archipelago/scripts/"
        echo "   Review and manually sync if needed"
        ssh "$TARGET_HOST" 'sudo ls -lh /opt/archipelago/scripts/'
    else
        echo "   ✅ No custom scripts found"
    fi
else
    echo "   ✅ No custom scripts directory"
fi

# Summary
echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  Sync Complete!                                                ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo "Configuration files captured:"
ls -lh "$CONFIG_DIR"
echo ""
echo "Next steps:"
echo "  1. Review the captured configurations"
echo "  2. Build backend: ./scripts/build-backend.sh"
echo "  3. Build frontend: ./scripts/build-frontend.sh"
echo "  4. Update integration script to use these configs"
echo "  5. Build ISO: ./build-debian-iso.sh"
echo ""
