#!/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"

    #this table shoud have a defult value. Shoud be in upgrade.pl to new version
    `mysql -e 'alter table userSession MODIFY COLUMN userId char(22) NOT NULL DEFAULT "0";' $connection_info ` && break
    `mysql -e 'alter table assetVersionTag MODIFY COLUMN name char(255) NOT NULL DEFAULT "default";' $connection_info ` && break
    `mysql -e 'alter table assetVersionTag MODIFY COLUMN createdBy char(22) NOT NULL DEFAULT "3";' $connection_info ` && break
    `mysql -e 'alter table assetVersionTag MODIFY COLUMN committedBy char(22) NOT NULL DEFAULT "3";' $connection_info ` && break
    `mysql -e 'alter table assetVersionTag MODIFY COLUMN lockedBy char(22) NOT NULL DEFAULT "3";' $connection_info ` && break
    `mysql -e 'alter table assetVersionTag MODIFY COLUMN groupToUse char(22) NOT NULL DEFAULT "3";' $connection_info ` && break
    `mysql -e 'alter table assetVersionTag MODIFY COLUMN workflowId char(22) NOT NULL DEFAULT "";' $connection_info ` && break

    `mysql -e 'alter table WorkflowInstance MODIFY COLUMN workflowId char(22) NOT NULL DEFAULT "";' $connection_info ` && break
    `mysql -e 'alter table WorkflowInstance MODIFY COLUMN currentActivityId char(22) NOT NULL DEFAULT "";' $connection_info ` && break
    if [ "$db_version" != "$code_version" ];then
        perl -Ilib sbin/wgd reset --upgrade --verbose --config-file=$configfile --webgui-root=/data/WebGUI/
        ### alter table userSession MODIFY COLUMN userId char(22) NOT NULL DEFAULT '0';

        ## 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

service apache2 start

while true; do
    echo "Starting Apache web server..."
    sleep 60
done    

apachectl -DFOREGROUND
