#!/bin/bash
SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

if [ "$(command -v sqlite3)" == "" ]
then
    echo "SQLite3 is not installed. Install it and try again."
    exit -1
fi

if [ "$(command -v php)" == "" ]
then
    echo "PHP is not installed. Install it and try again."
    exit -2
fi

if [ "$(php -m | grep sqlite3)" == "" ]
then
    echo "PHP module sqlite3 is not installed. Install it and try again."
    exit -3
fi

if [ "$(command -v node)" == "" ]
then
    echo "NODE.js is not installed. Install it and try again."
    exit -4
fi

# TODO: FIX, not working for this module
#if ! node -r requireg /dev/null 2> /dev/null
#then
#    echo "NODE.js module requireg is not installed. Install it and try again."
#    exit -5
#fi


if ! node -r dateformat /dev/null 2> /dev/null
then
    echo "NODE.js module dateformat is not installed. Install it and try again."
    exit -5
fi

if ! node -r request /dev/null 2> /dev/null
then
    echo "NODE.js module request is not installed. Install it and try again."
    exit -6
fi

if ! node -r querystring /dev/null 2> /dev/null
then
    echo "NODE.js module querystring is not installed. Install it and try again."
    exit -7
fi

if ! node -r http /dev/null 2> /dev/null
then
    echo "NODE.js module http is not installed. Install it and try again."
    exit -8
fi

if ! node -r fs /dev/null 2> /dev/null
then
    echo "NODE.js module fs is not installed. Install it and try again."
    exit -9
fi

clear_keys=0
clear_data=0
for i in "$@"
do
    if [[ $i == "--clear-keys" ]] ; then
        clear_keys=1;
    elif [[ $i == "--clear-data" ]] ; then
        clear_data=1;
    fi
done


if [ -f $SCRIPTPATH/application/sw.sqlite ] && [ $clear_keys == 0 ]
then
    echo "Key database exist. It will not be overwritten. Use the --clear-keys argument to override."
else
    echo "Setting up keys..."
    #rm $SCRIPTPATH/application/sw.sqlite
    #sqlite3 $SCRIPTPATH/application/sw.sqlite < $SCRIPTPATH/install_data/install_base.sql
fi

if [ -f $SCRIPTPATH/data/sw.sqlite ] && [ $clear_data == 0 ]
then
    echo "User data database exist. It will not be overwritten. Use the --clear-data argument to override."
else
    echo "Setting up user tables..."
    #rm $SCRIPTPATH/data/sw.sqlite
    #sqlite3 $SCRIPTPATH/data/sw.sqlite < $SCRIPTPATH/install_data/install_data.sql
fi

echo "All done. You can start the web server by typing ./start_server or edit the config file for the server options"
