#!/bin/bash

# script that runs when the docker container starts
echo "Starting WebGUI entrypoint script with:"
 perl -Ilib sbin/wgd ls
echo "Starting WebGUI entrypoint script..."
for configfile in `perl -Ilib sbin/wgd for-each`;do

    echo "Processing config file: $configfile"
    # wait for the db to come up and get our version so we know if we need to run upgrades
    connection_info=`perl -Ilib sbin/wgd db --config-file=$configfile --webgui-root=/data/WebGUI --print | sed "s/'//g" `
    while true; do
        db_version=`mysql --skip-column-names -e 'select webguiVersion from webguiVersion order by dateApplied desc limit 1;' $connection_info ` && break
        echo "waiting for the database to come up..."
        sleep 10
    done

    code_version=`perl -Ilib -e 'use WebGUI; print $WebGUI::VERSION;'`

    echo "code version $code_version"
    echo "database version $db_version for $configfile with configfile $configfile"

    if [ "$db_version" != "$code_version" ];then
        echo "Upgrading Webgui from $db_version to $code_version..." 
        #first we alter the userSession table to make sure that the userId has a default value This is required for the upgrade process to work correctly.   
        `mysql -e 'alter table userSession MODIFY COLUMN userId char(22) NOT NULL DEFAULT "0";' $connection_info `

        perl -Ilib sbin/wgd reset --upgrade --verbose --config-file=$configfile --webgui-root=/data/WebGUI/

        ## perl -Ilib sbin/wgd db --config-file=www.example.com --webgui-root=/data/WebGUI  

    fi

done

perl -I/data/WebGUI/lib sbin/spectre.pl --daemon

apachectl -DFOREGROUND
