#!/bin/bash
# ============================================
# Docker Auto-Rebuild and Restart Script
# Watches for file changes and automatically rebuilds Docker containers
# ============================================

# Configuration
WATCH_DIR="./mawidi-site"
COMPOSE_FILE="docker-compose.yml"
PROFILE="${1:-dev}"  # Default to dev profile
REBUILD_DELAY=2      # Seconds to wait before rebuilding (to batch changes)

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

# Function to print colored messages
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if fswatch is installed
check_dependencies() {
    if ! command -v fswatch &> /dev/null; then
        log_error "fswatch is not installed. Installing..."

        # Detect OS and install fswatch
        if [[ "$OSTYPE" == "darwin"* ]]; then
            # macOS
            if command -v brew &> /dev/null; then
                brew install fswatch
            else
                log_error "Homebrew not found. Please install fswatch manually: brew install fswatch"
                exit 1
            fi
        elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
            # Linux
            if command -v apt-get &> /dev/null; then
                sudo apt-get update && sudo apt-get install -y fswatch
            elif command -v yum &> /dev/null; then
                sudo yum install -y fswatch
            else
                log_error "Cannot install fswatch automatically. Please install it manually."
                exit 1
            fi
        else
            log_error "Unsupported OS. Please install fswatch manually."
            exit 1
        fi
    fi
}

# Function to rebuild and restart containers
rebuild_containers() {
    log_info "Changes detected! Rebuilding containers..."

    # Stop running containers
    docker-compose --profile "$PROFILE" down

    # Rebuild with cache
    if docker-compose --profile "$PROFILE" build --no-cache; then
        log_success "Build completed successfully!"

        # Start containers
        if docker-compose --profile "$PROFILE" up -d; then
            log_success "Containers restarted successfully!"

            # Show logs
            log_info "Showing logs (Ctrl+C to stop watching, containers will keep running)..."
            docker-compose --profile "$PROFILE" logs -f
        else
            log_error "Failed to start containers"
        fi
    else
        log_error "Build failed"
    fi
}

# Function to handle file changes with debouncing
handle_change() {
    local changed_file="$1"
    log_info "File changed: $changed_file"

    # Cancel previous rebuild timer if exists
    if [[ -n "$REBUILD_PID" ]]; then
        kill "$REBUILD_PID" 2>/dev/null
    fi

    # Start new rebuild timer
    (
        sleep "$REBUILD_DELAY"
        rebuild_containers
    ) &
    REBUILD_PID=$!
}

# Main watch loop
main() {
    log_info "Docker Auto-Rebuild Script"
    log_info "Watching directory: $WATCH_DIR"
    log_info "Using profile: $PROFILE"
    log_info "Press Ctrl+C to stop"

    # Check dependencies
    check_dependencies

    # Initial build and start
    rebuild_containers

    # Watch for changes
    fswatch -o "$WATCH_DIR" \
        --exclude "node_modules" \
        --exclude ".next" \
        --exclude ".git" \
        --exclude "*.log" \
        --exclude ".DS_Store" \
        --exclude "*.tmp" \
        --exclude "*.cache" \
        | while read change; do
            handle_change "$change"
        done
}

# Cleanup on exit
cleanup() {
    log_warning "Shutting down..."
    if [[ -n "$REBUILD_PID" ]]; then
        kill "$REBUILD_PID" 2>/dev/null
    fi
    docker-compose --profile "$PROFILE" down
    exit 0
}

# Set up signal handlers
trap cleanup SIGINT SIGTERM

# Run main function
main "$@"