#!/bin/bash

# Script to sync Docker compose and .env files to dotfiles repository
# This will help maintain all service configurations in version control

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
DOTFILES_DIR="/home/orangepi/dotfiles"
ORANGEPI_DIR="$DOTFILES_DIR/orangepi"
LOG_FILE="/tmp/sync-configs-$(date +%Y%m%d-%H%M%S).log"

# Initialize counters
TOTAL_SERVICES=0
SYNCED_SERVICES=0
TOTAL_FILES=0

# Function to log messages
log() {
    local level=$1
    shift
    local message="$@"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    case $level in
        "INFO")
            echo -e "${BLUE}[INFO]${NC} $message"
            ;;
        "SUCCESS")
            echo -e "${GREEN}[SUCCESS]${NC} $message"
            ;;
        "WARNING")
            echo -e "${YELLOW}[WARNING]${NC} $message"
            ;;
        "ERROR")
            echo -e "${RED}[ERROR]${NC} $message"
            ;;
    esac
    
    echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
}

# Function to find and sync files
sync_service_configs() {
    local service_name=$1
    local source_dir=$2
    local target_dir="$ORANGEPI_DIR/$service_name"
    
    log "INFO" "Processing $service_name from $source_dir..."
    
    # Create target directory if it doesn't exist
    mkdir -p "$target_dir" 2>/dev/null || {
        log "ERROR" "  Failed to create directory $target_dir"
        return 1
    }
    
    local files_copied=0
    
    # Find and copy docker-compose files
    for pattern in "docker-compose*.yml" "compose*.yml"; do
        for compose_file in $source_dir/$pattern; do
            if [[ -f "$compose_file" ]]; then
                local basename=$(basename "$compose_file")
                log "INFO" "  Copying $basename"
                if cp -f "$compose_file" "$target_dir/" 2>/dev/null; then
                    ((files_copied++))
                    ((TOTAL_FILES++))
                else
                    log "WARNING" "  Failed to copy $basename"
                fi
            fi
        done
    done
    
    # Find and copy .env files (including .env.example, etc)
    for env_file in $source_dir/.env*; do
        if [[ -f "$env_file" ]]; then
            local basename=$(basename "$env_file")
            log "INFO" "  Copying $basename"
            if cp -f "$env_file" "$target_dir/" 2>/dev/null; then
                ((files_copied++))
                ((TOTAL_FILES++))
            else
                log "WARNING" "  Failed to copy $basename"
            fi
        fi
    done
    
    # Find and copy any .enc files (encrypted configs)
    for enc_file in $source_dir/*.enc; do
        if [[ -f "$enc_file" ]]; then
            local basename=$(basename "$enc_file")
            log "INFO" "  Copying $basename"
            if cp -f "$enc_file" "$target_dir/" 2>/dev/null; then
                ((files_copied++))
                ((TOTAL_FILES++))
            else
                log "WARNING" "  Failed to copy $basename"
            fi
        fi
    done
    
    if [[ $files_copied -eq 0 ]]; then
        log "WARNING" "  No configuration files found for $service_name"
        # Remove empty directory
        rmdir "$target_dir" 2>/dev/null
        return 1
    else
        log "SUCCESS" "  ✓ Synced $files_copied files for $service_name"
        return 0
    fi
}

# Main execution
main() {
    log "INFO" "Starting configuration sync to dotfiles"
    log "INFO" "Log file: $LOG_FILE"
    log "INFO" "Target directory: $ORANGEPI_DIR"
    
    # Check if dotfiles directory exists
    if [[ ! -d "$DOTFILES_DIR" ]]; then
        log "ERROR" "Dotfiles directory not found at $DOTFILES_DIR"
        log "INFO" "Creating dotfiles directory..."
        mkdir -p "$DOTFILES_DIR"
    fi
    
    # Create orangepi directory if it doesn't exist
    mkdir -p "$ORANGEPI_DIR"
    
    # Find all service directories in home
    log "INFO" ""
    log "INFO" "Scanning for service directories..."
    
    # Create a temporary file to store unique service directories
    TEMP_SERVICES=$(mktemp)
    
    # Find all directories containing docker-compose files
    find /home/orangepi -maxdepth 3 \( -name "docker-compose*.yml" -o -name "compose*.yml" \) -type f 2>/dev/null | \
        grep -v dotfiles | \
        while read -r compose_path; do
            dirname "$compose_path"
        done | sort -u > "$TEMP_SERVICES"
    
    # Process each service directory
    while IFS= read -r service_dir; do
        if [[ -n "$service_dir" ]]; then
            local service_name=$(basename "$service_dir")
            ((TOTAL_SERVICES++))
            
            if sync_service_configs "$service_name" "$service_dir"; then
                ((SYNCED_SERVICES++))
            fi
        fi
    done < "$TEMP_SERVICES"
    
    rm -f "$TEMP_SERVICES"
    
    # Special handling for grouped services
    log "INFO" ""
    log "INFO" "Checking for grouped service directories..."
    for group_dir in /home/orangepi/media /home/orangepi/storage; do
        if [[ -d "$group_dir" ]]; then
            local group_name=$(basename "$group_dir")
            ((TOTAL_SERVICES++))
            
            if sync_service_configs "$group_name" "$group_dir"; then
                ((SYNCED_SERVICES++))
            fi
        fi
    done
    
    # Sync any root-level compose files
    log "INFO" ""
    log "INFO" "Checking for root-level compose files..."
    for compose_file in /home/orangepi/docker-compose*.yml /home/orangepi/compose*.yml; do
        if [[ -f "$compose_file" ]]; then
            local basename=$(basename "$compose_file")
            log "INFO" "Copying root-level $basename"
            if cp -f "$compose_file" "$ORANGEPI_DIR/" 2>/dev/null; then
                ((TOTAL_FILES++))
            fi
        fi
    done
    
    # Sync important scripts
    log "INFO" ""
    log "INFO" "Syncing important scripts..."
    mkdir -p "$ORANGEPI_DIR/scripts"
    for script in /home/orangepi/*.sh; do
        if [[ -f "$script" ]]; then
            local basename=$(basename "$script")
            # Skip sync scripts themselves
            if [[ "$basename" != "sync-configs-to-dotfiles"* ]]; then
                log "INFO" "  Copying script: $basename"
                cp -f "$script" "$ORANGEPI_DIR/scripts/" 2>/dev/null && ((TOTAL_FILES++))
            fi
        fi
    done
    
    # Create a README with service information
    log "INFO" ""
    log "INFO" "Creating service documentation..."
    cat > "$ORANGEPI_DIR/README.md" << EOF
# OrangePi Service Configurations

This directory contains Docker compose and environment files for all services running on the OrangePi.

## Services Synced

$(cd "$ORANGEPI_DIR" 2>/dev/null && find . -maxdepth 1 -type d -not -name "." -not -name "scripts" | sort | sed 's/^\.\//- /' || echo "No services found")

## Scripts

Important scripts are stored in the \`scripts/\` directory.

## Sync Information

- Last synced: $(date)
- Total services found: $TOTAL_SERVICES
- Successfully synced: $SYNCED_SERVICES
- Total files copied: $TOTAL_FILES
- Sync log: $LOG_FILE

## Usage

To deploy a service:
\`\`\`bash
cd /path/to/service
docker compose up -d
\`\`\`

## Important Notes

- .env files may contain sensitive information
- Remember to update passwords and secrets when deploying to a new system
- Some services may require additional setup (databases, volumes, etc.)

## Restoring to a New System

1. Clone this dotfiles repository
2. Copy service directories to desired locations
3. Update .env files with new passwords/secrets
4. Create necessary Docker networks and volumes
5. Run \`docker compose up -d\` in each service directory
EOF
    
    # Summary
    log "INFO" ""
    log "INFO" "==================== SUMMARY ===================="
    log "SUCCESS" "Configuration sync completed!"
    log "INFO" "Total services found: $TOTAL_SERVICES"
    log "INFO" "Successfully synced: $SYNCED_SERVICES"
    log "INFO" "Total files copied: $TOTAL_FILES"
    log "INFO" "Target directory: $ORANGEPI_DIR"
    log "INFO" "Full log available at: $LOG_FILE"
    
    # List what was synced
    if [[ $SYNCED_SERVICES -gt 0 ]]; then
        log "INFO" ""
        log "INFO" "Services synced:"
        cd "$ORANGEPI_DIR" 2>/dev/null && find . -maxdepth 1 -type d -not -name "." -not -name "scripts" | sort | sed 's/^\.\//  - /'
    fi
    
    # Git status hint
    if command -v git &> /dev/null && [[ -d "$DOTFILES_DIR/.git" ]]; then
        log "INFO" ""
        log "INFO" "To commit these changes to git:"
        log "INFO" "  cd $DOTFILES_DIR"
        log "INFO" "  git add orangepi/"
        log "INFO" "  git status  # Review changes"
        log "INFO" "  git commit -m \"Update OrangePi service configurations\""
        log "INFO" "  git push"
    fi
}

# Run main function
main "$@"