#!/bin/bash

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

set -euo pipefail

# 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"

# 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" | tee -a "$LOG_FILE"
            ;;
        "SUCCESS")
            echo -e "${GREEN}[SUCCESS]${NC} $message" | tee -a "$LOG_FILE"
            ;;
        "WARNING")
            echo -e "${YELLOW}[WARNING]${NC} $message" | tee -a "$LOG_FILE"
            ;;
        "ERROR")
            echo -e "${RED}[ERROR]${NC} $message" | tee -a "$LOG_FILE"
            ;;
    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..."
    
    # Create target directory if it doesn't exist
    mkdir -p "$target_dir"
    
    # Find and copy docker-compose files
    local compose_count=0
    for compose_file in "$source_dir"/docker-compose*.yml "$source_dir"/compose*.yml; do
        if [[ -f "$compose_file" ]]; then
            local basename=$(basename "$compose_file")
            log "INFO" "  Copying $basename"
            cp -f "$compose_file" "$target_dir/"
            ((compose_count++))
        fi
    done
    
    # Find and copy .env files
    local env_count=0
    for env_file in "$source_dir"/.env*; do
        if [[ -f "$env_file" ]]; then
            local basename=$(basename "$env_file")
            log "INFO" "  Copying $basename"
            cp -f "$env_file" "$target_dir/"
            ((env_count++))
        fi
    done
    
    # Find and copy any .enc files (encrypted configs)
    local enc_count=0
    for enc_file in "$source_dir"/*.enc; do
        if [[ -f "$enc_file" ]]; then
            local basename=$(basename "$enc_file")
            log "INFO" "  Copying $basename"
            cp -f "$enc_file" "$target_dir/"
            ((enc_count++))
        fi
    done
    
    if [[ $compose_count -eq 0 && $env_count -eq 0 && $enc_count -eq 0 ]]; then
        log "WARNING" "  No configuration files found for $service_name"
        # Remove empty directory
        rmdir "$target_dir" 2>/dev/null || true
    else
        log "SUCCESS" "  Synced $compose_count compose, $env_count env, $enc_count enc files"
    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"
        exit 1
    fi
    
    # Create orangepi directory if it doesn't exist
    mkdir -p "$ORANGEPI_DIR"
    
    # Counter for statistics
    local total_services=0
    local synced_services=0
    
    # Find all service directories in home
    log "INFO" "Scanning for service directories..."
    
    # Method 1: Look for directories with docker-compose files
    while IFS= read -r compose_path; do
        if [[ -n "$compose_path" ]]; then
            local service_dir=$(dirname "$compose_path")
            local service_name=$(basename "$service_dir")
            
            # Skip directories that are already in dotfiles
            if [[ "$service_dir" == *"dotfiles"* ]]; then
                continue
            fi
            
            ((total_services++))
            sync_service_configs "$service_name" "$service_dir"
            
            if [[ -d "$ORANGEPI_DIR/$service_name" ]]; then
                ((synced_services++))
            fi
        fi
    done < <(find /home/orangepi -maxdepth 3 -name "docker-compose*.yml" -o -name "compose*.yml" 2>/dev/null | grep -v dotfiles | sort -u)
    
    # Special handling for grouped services (media, storage, etc.)
    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++))
            sync_service_configs "$group_name" "$group_dir"
            
            if [[ -d "$ORANGEPI_DIR/$group_name" ]]; then
                ((synced_services++))
            fi
        fi
    done
    
    # Sync any root-level compose files
    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"
            cp -f "$compose_file" "$ORANGEPI_DIR/"
        fi
    done
    
    # Sync important scripts
    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 this sync script itself
            if [[ "$basename" != "sync-configs-to-dotfiles.sh" ]]; then
                log "INFO" "  Copying script: $basename"
                cp -f "$script" "$ORANGEPI_DIR/scripts/"
            fi
        fi
    done
    
    # Create a README with service information
    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

$(cd "$ORANGEPI_DIR" && find . -maxdepth 1 -type d -not -name "." -not -name "scripts" | sort | sed 's/^\.\//- /')

## Scripts

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

## Sync Information

- Last synced: $(date)
- Total services found: $total_services
- Successfully synced: $synced_services
- 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.)
EOF
    
    # Summary
    log "INFO" "==================== SUMMARY ===================="
    log "SUCCESS" "Configuration sync completed!"
    log "INFO" "Total services found: $total_services"
    log "INFO" "Successfully synced: $synced_services"
    log "INFO" "Target directory: $ORANGEPI_DIR"
    log "INFO" "Full log available at: $LOG_FILE"
    
    # Git status hint
    if command -v git &> /dev/null; then
        log "INFO" ""
        log "INFO" "To commit these changes to git:"
        log "INFO" "  cd $DOTFILES_DIR"
        log "INFO" "  git add orangepi/"
        log "INFO" "  git commit -m \"Update OrangePi service configurations\""
    fi
}

# Run main function
main "$@"