#!/bin/bash

wfc_work_dir=/opt/wfc
docker_work_dir=${wfc_work_dir}/docker

# Get the new version number
new_version=$(grep '^VERSION_ID=' ${docker_work_dir}/env/wfc-release | cut -d'=' -f2 | tr -d '"')

# Get the original version number
if [ -f ${docker_work_dir}/.wfc-release ]; then
    old_version=$(grep '^VERSION_ID=' ${docker_work_dir}/.wfc-release | cut -d'=' -f2 | tr -d '"')
else 
    old_version=$new_version
fi

# Convert the version number to a comparable format
version_to_number() {
    echo "$1" | awk -F. '{ printf("%d%03d%03d\n", $1,$2,$3); }'
}

new_version_num=$(version_to_number $new_version)
old_version_num=$(version_to_number $old_version)

# Find and execute all version directories higher than the original version number
for dir in ${docker_work_dir}/mysql/db/upgrade/*; do
    version=$(basename $dir)
    version_num=$(version_to_number $version)
    if [ $version_num -gt $old_version_num ] && [ $version_num -le $new_version_num ]; then
        echo "Executing upgrade for version $version"
        ${wfc_work_dir}/bin/wfcupgdb.sh $version
    fi
done

# Update the version number
cp -f ${docker_work_dir}/env/wfc-release ${docker_work_dir}/.wfc-release
echo "Upgrade complete"