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

reinstall=0
for i in "$@"
do
    if [[ $i == "--reinstall" ]] ; then
        reinstall=1;
    fi
done

if [ -f $SCRIPTPATH/data/sw.sqlite ] && [ $reinstall == 0 ]
then
    echo "User data database exist. It will not be overwritten. Use the --reinstall argument to override."
else
    echo "Setting up user tables..."
    rm $SCRIPTPATH/data/sw.sqlite
    cp $SCRIPTPATH/installer/data_empty.sqlite $SCRIPTPATH/data/sw.sqlite
fi

# Ask for admin user and password
correct=0
while [ $correct -eq 0 ]
do
    read -p "Enter admin username:" $user
    if [[ $user =~ ^[a-zA-Z0-9]{4, 32}$ ]]
    then
        correct=1
    else
        echo "Invalid username. Use numbers or letters. Length must be between 4 and 32 characters."
    fi
done
correct=0
while [ $correct -eq 0]
do
    read -p "Enter admin email:" $mail
    if [[ $mail =~ ^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$ ]]
    then
        correct=1
    else
        echo "Invalid email."
    fi
match=0
while [ $match -eq 0 ]
do
    read -s -p "Enter password:" $password
    read -s -p "Enter password:" $passwordRepeat
    if [ "$password" = "$passwordRepeat" ]
    then
        match=1
    else
        echo "Paswords do not match"
    fi
done
hash=$(echo -n $password | sha256sum)
api=$(head -1 <(fold -w 16  <(tr -dc 'a-zA-Z0-9' < /dev/urandom)))

query="INSERT INTO USER VALUES (0, '$user', '$mail', '$hash', '$api', 1, 0);"

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