#!/bin/sh

# Path to the version tracking file
VERSION_FILE=$2
# Path to migration scripts
MIGRATION_DIR=$1


# Print usage if no arguments are provided
if [ -z "$MIGRATION_DIR" ] || [ -z "$VERSION_FILE" ]; then
    echo "Usage: $0 <migration_dir> <version_file>"
    exit 1
fi

# Create the version file if it doesn't exist
if [ ! -f $VERSION_FILE ]; then
    echo "000" > $VERSION_FILE
fi

# Print current version
echo "Current config version: $(cat $VERSION_FILE)"

# Read the current configuration version
CURRENT_VERSION=$(cat $VERSION_FILE)

# Find all migration scripts and sort them
sorted_migrations=$(find $MIGRATION_DIR -type f -name "*.sh" | sort)

if [ -z "$sorted_migrations" ]; then
    echo "No migration scripts found"
    exit 0
fi

# Loop through all migration scripts in order
for script in $sorted_migrations; do
    # Extract the migration number from the filename
    MIGRATION_NUM=$(basename $script | cut -d'_' -f1)
    
    # Apply the migration if it hasn't been applied yet
    if [ "$CURRENT_VERSION" -lt "$MIGRATION_NUM" ]; then
        echo "Applying migration $script"
        sh $script
        echo "$MIGRATION_NUM" > $VERSION_FILE
    fi
done

# Print the new version
echo "New config version: $(cat $VERSION_FILE)"
