#!/bin/bash

wfc_work_dir=/opt/wfc
docker_work_dir=${wfc_work_dir}/docker
mysql_sql_dir=${docker_work_dir}/mysql/db
docker_mysql_conf_d=/etc/mysql/conf.d
docker_my_conf_file=${docker_mysql_conf_d}/my.cnf
mysql_container_name=wfc-mysql

execute_sql_scripts() {
    version=$1
    cd ${mysql_sql_dir}
    for sql in ./upgrade/${version}/*.sql; do
        if [ -f "$sql" ]; then        
            echo -n "Execute SQL script: ${sql} ... "
            docker exec -i ${mysql_container_name} mysql --defaults-extra-file=${docker_my_conf_file} < ${sql}
            if [ $? = 0 ]; then
                echo "done" 
            fi
        else
            echo "No SQL files found in ./upgrade/${version}/"
        fi                       
    done
}

if [ -z "$1" ]; then
    # No parameter, traverse all subdirectories in upgrade directory
    for dir in ${mysql_sql_dir}/upgrade/*; do
        if [ -d "$dir" ]; then
            version=$(basename $dir)
            echo "Executing upgrade for version $version"
            execute_sql_scripts $version
        fi
    done
else
    # Parameter provided, execute for the specific version or database name
    ver_or_dbname=$1
    if [ ! -d ${mysql_sql_dir}/upgrade/${ver_or_dbname} ]; then
        echo "No upgrade scripts found for ${ver_or_dbname}"
        exit 1
    fi
    execute_sql_scripts $ver_or_dbname
fi