#!/bin/bash

# OptionEdge Docker Upgrade Script
# This script handles the upgrade process for Docker deployments

set -e

# Configuration
DOCKER_COMPOSE_FILE="docker-compose.yml"
BACKUP_DIR="./backups"
TEMP_DIR="./temp"
LOG_FILE="./upgrade.log"

# Create necessary directories
mkdir -p "$BACKUP_DIR"
mkdir -p "$TEMP_DIR"

# Log function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Backup function
backup_compose_file() {
    local backup_file="$BACKUP_DIR/docker-compose-$(date '+%Y%m%d%H%M%S').yml"
    cp "$DOCKER_COMPOSE_FILE" "$backup_file"
    log "Backed up docker-compose.yml to $backup_file"
}

# Check if docker-compose is installed
if ! command -v docker-compose &> /dev/null; then
    log "ERROR: docker-compose is not installed. Please install it first."
    exit 1
fi

# Check if docker is running
if ! docker info &> /dev/null; then
    log "ERROR: Docker is not running. Please start Docker first."
    exit 1
fi

# Check if docker-compose.yml exists
if [ ! -f "$DOCKER_COMPOSE_FILE" ]; then
    log "ERROR: $DOCKER_COMPOSE_FILE not found in the current directory."
    exit 1
fi

# Display current versions
log "Current configuration:"
log "Engine: $(grep -E "image: 'optionedge/engine:" "$DOCKER_COMPOSE_FILE" | head -1)"
log "Upgrade Service: $(grep -E "image: 'optionedge/upgrade-service:" "$DOCKER_COMPOSE_FILE" | head -1)"

# Backup the current docker-compose.yml
backup_compose_file

# Function to update the docker-compose.yml file
update_compose_file() {
    local new_version=$1
    local temp_file="$TEMP_DIR/docker-compose.tmp"
    
    log "Updating application to version $new_version"
    
    # Update both engine and upgrade-service images
    sed -E "s|image: 'optionedge/engine:([^']*)'|image: 'optionedge/engine:$new_version'|g" "$DOCKER_COMPOSE_FILE" | \
    sed -E "s|image: 'optionedge/upgrade-service:([^']*)'|image: 'optionedge/upgrade-service:$new_version'|g" > "$temp_file"
    
    mv "$temp_file" "$DOCKER_COMPOSE_FILE"
    log "Updated $DOCKER_COMPOSE_FILE successfully (both engine and upgrade-service)"
}

# Function to restart the containers with force recreate
restart_containers() {
    log "Pulling new Docker images..."
    docker-compose pull
    
    log "Stopping containers..."
    docker-compose down
    
    log "Starting containers with new versions (force recreate)..."
    docker-compose up -d --force-recreate
    
    log "Containers restarted successfully with new images"
}

# Function to restart specific containers with force recreate
restart_specific_containers() {
    local containers=$1
    
    if [ -z "$containers" ]; then
        log "No containers specified for restart"
        return 1
    fi
    
    log "Pulling new images for containers: $containers"
    docker-compose pull $containers
    
    log "Recreating containers: $containers"
    docker-compose up -d --force-recreate $containers
    
    log "Containers recreated successfully with new images"
}

# Main upgrade process
main() {
    local version=$1
    local action=$2
    
    # Handle restart command
    if [ "$version" == "restart" ]; then
        log "Restarting application container..."
        restart_specific_containers "engine_local"
        exit 0
    fi
    
    # Handle upgrade command
    if [ -z "$version" ]; then
        log "Usage: $0 <version> [restart]"
        log "   or: $0 restart"
        log "Example: $0 1.0.76"
        log "Example: $0 1.0.76 restart"
        exit 1
    fi
    
    log "Starting upgrade process to version $version"
    
    update_compose_file "$version"
    
    # Check if restart was requested
    if [ "$action" == "restart" ]; then
        restart_containers
    else
        # Ask for confirmation before restarting
        read -p "Do you want to restart the containers now? (y/n): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            restart_containers
        else
            log "Containers not restarted. Please run 'docker-compose down && docker-compose up -d' manually to apply the changes."
        fi
    fi
    
    log "Upgrade process completed"
}

# Execute the main function with all arguments
main "$@"