#!/bin/bash
# WHP Migration Application Script
# Applies SQL migrations between two versions

# Exit on any error
set -e

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

# Check arguments
if [ $# -ne 3 ]; then
    echo "Usage: $0 <current_version> <new_version> <migration_dir>"
    echo "Example: $0 2025.01.1 2025.01.2 /root/whp/sql/migrations"
    exit 1
fi

CURRENT_VERSION="$1"
NEW_VERSION="$2"
MIGRATION_DIR="$3"

# Validate migration directory exists
if [ ! -d "$MIGRATION_DIR" ]; then
    echo -e "${RED}Error: Migration directory not found: $MIGRATION_DIR${NC}"
    exit 1
fi

# Function to compare versions (YYYY.MM.N format)
version_compare() {
    # Convert version to comparable number: YYYYMMN
    local v1=$(echo "$1" | sed 's/\.//g')
    local v2=$(echo "$2" | sed 's/\.//g')
    
    if [ "$v1" -lt "$v2" ]; then
        echo "-1"
    elif [ "$v1" -gt "$v2" ]; then
        echo "1"
    else
        echo "0"
    fi
}

echo "Applying migrations from $CURRENT_VERSION to $NEW_VERSION"

# Get list of all version directories
cd "$MIGRATION_DIR"
VERSIONS=($(ls -d */ 2>/dev/null | sed 's/\///' | sort -V))

if [ ${#VERSIONS[@]} -eq 0 ]; then
    echo "No migration versions found"
    exit 0
fi

# Track if any migrations were applied
MIGRATIONS_APPLIED=0

# Apply migrations for each version between current and new
for VERSION in "${VERSIONS[@]}"; do
    # Check if this version is greater than current and less than or equal to new
    COMPARE_CURRENT=$(version_compare "$VERSION" "$CURRENT_VERSION")
    COMPARE_NEW=$(version_compare "$VERSION" "$NEW_VERSION")
    
    if [ "$COMPARE_CURRENT" = "1" ] && [ "$COMPARE_NEW" -le "0" ]; then
        
        echo ""
        echo "Processing migrations for version $VERSION..."
        
        # Get all SQL files in this version directory
        SQL_FILES=($(find "$VERSION" -name "*.sql" -type f | sort))
        
        if [ ${#SQL_FILES[@]} -eq 0 ]; then
            echo "  No migrations found for version $VERSION"
            continue
        fi
        
        for SQL_FILE in "${SQL_FILES[@]}"; do
            echo -n "  Applying $(basename "$SQL_FILE")... "
            
            # Apply the migration
            if mysql < "$SQL_FILE" 2>/tmp/migration_error.log; then
                echo -e "${GREEN}✓${NC}"
                MIGRATIONS_APPLIED=$((MIGRATIONS_APPLIED + 1))
            else
                echo -e "${RED}✗${NC}"
                echo -e "${RED}Error applying migration: $SQL_FILE${NC}"
                
                # Show error details
                if [ -f /tmp/migration_error.log ]; then
                    echo "Error details:"
                    cat /tmp/migration_error.log
                    rm -f /tmp/migration_error.log
                fi
                
                exit 1
            fi
        done
    fi
done

# Clean up
rm -f /tmp/migration_error.log

# Summary
echo ""
if [ $MIGRATIONS_APPLIED -eq 0 ]; then
    echo -e "${YELLOW}No migrations needed${NC}"
else
    echo -e "${GREEN}Successfully applied $MIGRATIONS_APPLIED migration(s)${NC}"
fi