#!/bin/bash

if [ -z "$POS_CONFIG" ]
then
	export POS_CONFIG=data
	echo "Using default POS config: $POS_CONFIG"
fi

if [ -z "$POS_NODE" ]
then
	export POS_NODE=server
	echo "Using default POS node: $POS_NODE"
fi

if [ -z "$POS_PORT" ]
then
	export POS_PORT=14000
	echo "Using default POS port: $POS_PORT"
fi

OS=$(uname)
echo $OS
MARCH=$(uname -m)
BASEDIR=$(pwd)
EXECUTABLE=hv
NOHUP='nohup'

if [ "$OS" == "Linux" ]; then
	LINUXFLAVOR=$(cat /etc/os-release | grep "^ID=" | cut -d "=" -f 2 | sed 's/"//g')
fi

if [ -d ./genesis ]; then
	EXECUTABLE=genclient
elif [ ! -d $BASEDIR ]; then
	echo "Unable to determine correct MW:SDK binaries directory: $BASEDIR"
	exit 1
fi

if [ ! -f $BASEDIR/bin/$EXECUTABLE ]; then
	echo "Unable to find executable: $BASEDIR/bin/$EXECUTABLE"
	exit 1
fi

export POS_BIN=$BASEDIR/bin
export PYTHONHOME=$BASEDIR/python
export DYLD_LIBRARY_PATH=$POS_BIN:$PYTHONHOME/lib
export LD_LIBRARY_PATH=$DYLD_LIBRARY_PATH
echo $LD_LIBRARY_PATH
export POS_DATADIR=$BASEDIR/data
export NODE_DIR=$POS_DATADIR/$POS_NODE
export HVLOGFILE=$NODE_DIR/logs/hv.log
export HVLOGLEVEL=56
export HVMAXLOGFILES=10
export GENLOGFILE=$NODE_DIR/logs/genesis.log
export GENLOGLEVEL=60
export DATABASEDIR=$NODE_DIR/databases

echo POS_DATADR: $POS_DATADIR
echo POS_NODE: $POS_NODE

if [ ! -d $POS_DATADIR ]
then
    echo "Invalid data/node directory: $POS_DATADIR"
    echo "Please verify if POS_NODE are correct: POS_NODE=$POS_NODE"
    exit 1
fi

if [ ! -f $NODE_DIR/bundles/loader.cfg ]
then
    echo "Invalid data/node directory. Base loader.cfg file was not found: $NODE_DIR/bundles/loader.cfg"
    echo "Please verify if POS_NODE are correct: POS_NODE=$POS_NODE"
    exit 1
fi

if [ ! -f $NODE_DIR/bundles/license.gz ]
then
    echo "Invalid data/node directory. License file was not found under $NODE_DIR/bundles directory."
    echo "Please verify if POS_NODE are correct: POS_NODE=$POS_NODE"
    exit 1
fi

GENSTATUS="NOTHING"

UNAME=`id -u -n`
if [ ${UNAME} == "root" ]; then
	echo "Invalid user"
	exit 1
fi

run_genclient() {
    while true; do
        if [ -f sqlite3 ]; then
            echo "Started: $(date)"
            for db_file in "$DATABASEDIR"/*.db*; do
                echo Checking Database "$db_file"...
                sqlite3 "$db_file" "SELECT count(*) FROM sqlite_schema" > /dev/null
                sqlite3 "$db_file" "PRAGMA integrity_check;" | grep -qi "ok" || {
                    echo "Fixing Database $db_file..."
                    sqlite3 "$db_file" ".recover" | sqlite3 "$DATABASEDIR/new.db"
                    mv "$db_file" "$db_file.broken"
                    mv "$DATABASEDIR/new.db" "$db_file"
                }
            done
            echo "Finished: $(date)"
        fi

        echo "Starting genclient..."
        if [ "$GENSTATUS" = "NOTHING" ]; then
            ./genclient --local ../genesis --data $NODE_DIR --node $POS_NODE --notime 1 --force 1 -q >/dev/null 2>1
            ERRORLEVEL=$?
            echo "updates directory created. Exit code: $ERRORLEVEL"
        fi

        if [ "$GENSTATUS" = "SUCCESS" ]; then
            echo "Updated with success, running Hypervisor"
            GENSTATUS="NOTHING"
            ./genclient --updated -q >/dev/null
            ERRORLEVEL=$?
            echo "HV exited with $ERRORLEVEL"
        fi

        if [ "$GENSTATUS" = "RESTORE" ]; then
            GENSTATUS="NOTHING"
            ./genclient -r -q >/dev/null
            ERRORLEVEL=$?
        fi

        if [ $ERRORLEVEL -eq 0 ]; then
		    echo "Hypervisor successfully terminated, also terminating"
			exit 0
        elif [ $ERRORLEVEL -eq 201 ]; then
            echo "Store Wide reset, running genclient again"
        elif [ $ERRORLEVEL -eq 13 ]; then
            echo "Running gencopy..."
            ./gencopy "gencopy" 0 -q ../updates/data "$NODE_DIR" ../updates/bin ../bin ../updates/apache ../apache ../updates/chrome ../chrome ../updates/python ../python ../updates/python3 ../python3 ../updates/src ../src ../updates/root ../ >/dev/null
            if [ $? -eq 0 ]; then
                echo "Finished gencopy Update... Running HV..."
                GENSTATUS="SUCCESS"
            else
                echo "Failed genclient Update... Running Restore..."
                GENSTATUS="RESTORE"
            fi
            pwd
        else
            echo "Invalid return code $ERRORLEVEL, exiting"
            exit $ERRORLEVEL
        fi
    done
}

if [ "$EXECUTABLE" = "genclient" ]; then
    cd "$POS_BIN"
    run_genclient
elif [ "$EXECUTABLE" = "hv" ]; then
    cd "$POS_BIN"
    $NOHUP ./hv --service --data $POS_DATADIR --node $POS_NODE --tcp 127.0.0.1:$POS_PORT>/dev/null 2>&1 &
    echo "$POS_PORT	$POS_DATADIR" > $BASEDIR/$!.hvpid
    popd>/dev/null
fi

error_exit() {
    echo "Erro ao executar: $*"
    exit 1
}
