#!/usr/bin/env bash

#**************************************************************************************
#*
#*     Project:    kvmstoreserver
#*     File name:  kvmss-installer.sh
#*     Version:    1.0.0
#*     Date:       2018-02-06
#*
#*     Autor:      Bogdanovic Theodor
#*     Contact:    t.bogdanovic@hotmail.com
#*
#*     License:    GPLv3
#*
#**************************************************************************************
#**************************************************************************************
#* Copyright 2018 Bogdanovic Theodor
#*
#* This file is part of kvmstoreserver.
#*
#* kvmstoreserver is free software: you can redistribute it and/or modify
#* it under the terms of the GNU General Public License as published by
#* the Free Software Foundation, either version 3 of the License, or
#* (at your option) any later version.
#*
#* kvmstoreserver is distributed in the hope that it will be useful,
#* but WITHOUT ANY WARRANTY; without even the implied warranty of
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#* GNU General Public License for more details.
#*
#* You should have received a copy of the GNU General Public License
#* along with kvmstoreserver.  If not, see <http://www.gnu.org/licenses/>.
#**************************************************************************************/
#**************************************************************************************
#*     Further explanations:  This source code is under the license specified by the
#*                            Autor above. Core components or other packages are still
#*                            in source code form, under the license specified by the
#*                            respective author.
#*
#**************************************************************************************

### Variables ###

IP_OR_DOMNAME=""
INSTALL_ROOT="/home/kvmstoreserver/kvmstoreserver"
USERNAME="kvmstoreserver"
USER_PASSWD=""
SELECT_ANSWER=""
EXIST_AN_INSTALLATION=100

### Functions ###

function window::if_user_root() 
{
    if [ `id -u` -ne 0 ]
    then
        whiptail --title "KVM Store Server Installer" --msgbox "You need root rights to run this installer. Please try again with sudo kvmss-installer" 10 70
        exit 1
    fi
}

function window::run_installer()
{
    local kind=$1

    if [ $kind == "install" ] 
    then
        if (! whiptail --title "KVM Store Server Installer" --yesno "Do you want to start installing of the KVM Store Server" 8 70)
        then
            exit 0
        fi
    elif [ $kind == "delete" ]
    then
        if (! whiptail --title "KVM Store Server Installer" --yesno "Do you want to start deletion of the KVM Store Server - Attention, this will also erase the stored data!" 8 70)
        then
            exit 0
        fi
    else
        exit 1
    fi
}

function window::enter_ip_or_name()
{
    name=$(whiptail --inputbox "Please enter the IP address of your computer on which the KVM Store Server should listen, alternatively you can also use the valid domain name of your computer - Example -> 192.168.0.5 or my-computer.my-domain.com You can also leave this field blank, then the server listens to all interfaces - THIS CONFIGURATION IS NOT RECOMMENDED!" 12 90 --title "KVM Store Server Installer" 3>&1 1>&2 2>&3)

    answer=$?
    if [ $answer = 0 ]; then
        IP_OR_DOMNAME=$name
    else
        exit 0
    fi
}

function core::exist_an_installation()
{
    if [ -d $INSTALL_ROOT ] 
    then
        EXIST_AN_INSTALLATION=1
    else
        EXIST_AN_INSTALLATION=0
    fi
}

function window::enter_passwd() 
{
    for (( ; ; ))
    do
        passwd_1=$(whiptail --passwordbox "Please enter a password for the new linux user kvmstoreserver - Please do not use backslash" 8 60 --title "KVM Store Server Installer" 3>&1 1>&2 2>&3)

        answer=$?
        [ $answer != 0 ] && exit 0

        passwd_2=$(whiptail --passwordbox "Please enter the password again" 8 60 --title "KVM Store Server Installer" 3>&1 1>&2 2>&3)

        answer=$?
        if [ $answer = 0 ]
        then
            if [ ${passwd_1} == ${passwd_2} ] && [ ! -z ${passwd_2} ]
            then
                USER_PASSWD=$passwd_2
                break
            else
                whiptail --title "KVM Store Server Installer" --msgbox "The passwords do not match. Try again" 8 45
                continue
            fi
        else             
            exit 0
        fi
    done 
}

function core::create_kvmss_user()
{
    sudo useradd $USERNAME -m
    echo -e "$USER_PASSWD\n$USER_PASSWD\n" | sudo passwd $USERNAME
}

function core::create_folder_struct()
{
    sudo mkdir $INSTALL_ROOT
    sudo mkdir $INSTALL_ROOT/bin
    sudo mkdir $INSTALL_ROOT/etc
    sudo mkdir $INSTALL_ROOT/warehouse
    sudo mkdir $INSTALL_ROOT/utils
    sudo mkdir $INSTALL_ROOT/var
    sudo mkdir $INSTALL_ROOT/var/log
}

function core::change_rights()
{
    sudo chmod u+rw $INSTALL_ROOT/var/log
    sudo chmod g+rw $INSTALL_ROOT/var/log
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/var/log

    sudo chmod u+rw $INSTALL_ROOT/var
    sudo chmod g+rw $INSTALL_ROOT/var
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/var

    sudo chmod u+rw $INSTALL_ROOT/warehouse
    sudo chmod g+rw $INSTALL_ROOT/warehouse
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/warehouse
    
    sudo chmod u+rw $INSTALL_ROOT/utils
    sudo chmod g+rw $INSTALL_ROOT/utils
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/utils

    sudo chmod u+rw $INSTALL_ROOT/etc
    sudo chmod g+rw $INSTALL_ROOT/etc
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/etc

    sudo chmod u+rw $INSTALL_ROOT/bin
    sudo chmod g+rw $INSTALL_ROOT/bin
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/bin

    sudo chmod u+rwx $INSTALL_ROOT/utils/inject_disk
    sudo chmod g+rwx $INSTALL_ROOT/utils/inject_disk
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/utils/inject_disk

    sudo chmod u+rwx $INSTALL_ROOT/bin/kvmstoreserver
    sudo chmod g+rwx $INSTALL_ROOT/bin/kvmstoreserver
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/bin/kvmstoreserver

    sudo chmod u+rw $INSTALL_ROOT/etc/kvmstoreserver.conf
    sudo chmod g+rw $INSTALL_ROOT/etc/kvmstoreserver.conf
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT/etc/kvmstoreserver.conf

    sudo chmod u+rw $INSTALL_ROOT
    sudo chmod g+rw $INSTALL_ROOT
    sudo chown $USERNAME:$USERNAME $INSTALL_ROOT
}

function core::copy_files()
{
    sudo cp ./data/bin/kvmstoreserver $INSTALL_ROOT/bin/kvmstoreserver
    sudo cp ./data/utils/inject_disk $INSTALL_ROOT/utils/inject_disk
    sudo cp ./data/etc/kvmstoreserver.conf $INSTALL_ROOT/etc/kvmstoreserver.conf
    sudo cp ./data/init/kvmstoreserver.service /etc/systemd/system/kvmstoreserver.service
}

function core::install_and_run_daemon()
{
    sudo systemctl daemon-reload
    sudo systemctl start kvmstoreserver.service
    sudo systemctl enable kvmstoreserver.service
}

function core::replace_server_name()
{
    sudo sed -i -e "s/http_hostname            =   /http_hostname            =   $IP_OR_DOMNAME/g" $INSTALL_ROOT/etc/kvmstoreserver.conf
}

function window::select_action()
{

    if [ $EXIST_AN_INSTALLATION = 0 ]
    then
        selection=$(whiptail --title "KVM Store Server Installer" --menu "Choose an option" 9 70 2 \
            "Install" "Installs the KVM Store Server on the hard disk" 3>&1 1>&2 2>&3)

        answer=$?
        [ $answer != 0 ] && exit 0
    elif [ $EXIST_AN_INSTALLATION = 1 ]
    then
        selection=$(whiptail --title "KVM Store Server Installer" --menu "Choose an option" 9 70 2 \
            "Remove " "Delete the KVM Store Server completely from the hard disk" 3>&1 1>&2 2>&3)
        answer=$?
        [ $answer != 0 ] && exit 0
    fi

        SELECT_ANSWER=$selection
}

function window::finish_text()
{
    local kind=$1

    if [ $kind == "install" ] 
    then
        if (whiptail --title "KVM Store Server Installer" --msgbox "The installation is complete, the server is now running - The configuration file can be found at /home/kvmstoreserver/kvmstoreserver/etc/kvmstoreserver.conf. There you can make all relevant settings. After a change in the configuration file, you may need to run - sudo systemctl restart kvmstoreserver.service - in the console" 13 90)
        then
            exit 0
        fi
    elif [ $kind == "delete" ]
    then
        if (whiptail --title "KVM Store Server Installer" --msgbox "The KVM Store Server is completlly deleted from your Harddisk" 8 70)
        then
            exit 0
        fi
    fi
}

function main::install()
{
        window::run_installer "install"
        window::enter_ip_or_name
        window::enter_passwd

    {
        echo XXX && echo 10 && echo "Creating kvmstoreserver user" && echo XXX && core::create_kvmss_user > /dev/null 2>&1
        echo XXX && echo 20 && echo "Creating folder structure" && echo XXX && core::create_folder_struct  > /dev/null 2>&1
        echo XXX && echo 40 && echo "Copy files" && echo XXX && core::copy_files  > /dev/null 2>&1
        echo XXX && echo 50 && echo "Configure config file" && echo XXX && core::replace_server_name  > /dev/null 2>&1
        echo XXX && echo 70 && echo "Changing rights" && echo XXX && core::change_rights  > /dev/null 2>&1
        echo XXX && echo 100 && echo "Install an run kvmstoreserver daemon" && echo XXX && core::install_and_run_daemon  > /dev/null 2>&1
    } | whiptail --title "Please wait KVM Store Server will be installed" --gauge "Start" 6 60 0

    window::finish_text "install"
}

function main::remove()
{
    window::run_installer "delete"

    {
        echo XXX && echo 10 && echo "Killing all processes of user kvmstoreserver" && echo XXX && sudo killall --user $USERNAME > /dev/null 2>&1
        echo XXX && echo 20 && echo "Stopping kvmstoreserver service" && echo XXX && sudo systemctl stop kvmstoreserver.service -f > /dev/null 2>&1
        echo XXX && echo 40 && echo "Deactivating kvmstoreserver service" && echo XXX && sudo systemctl disable kvmstoreserver.service -f > /dev/null 2>&1
        echo XXX && echo 50 && echo "Removing kvmstoreserver service" && echo XXX && sudo rm /etc/systemd/system/kvmstoreserver.service  > /dev/null 2>&1
        echo XXX && echo 80 && echo "Reloading Systemd init system" && echo XXXsudo systemctl daemon-reload > /dev/null 2>&1

        echo XXX && echo 100 && echo "Deleting kvmstoreserver user and DATA" && echo XXX && sudo deluser $USERNAME --remove-home > /dev/null 2>&1
    } | whiptail --title "Please wait, KVM Store Server will be deleted" --gauge "Start" 6 60 0

    window::finish_text "delete"
}

### MAIN ###

window::if_user_root
core::exist_an_installation
window::select_action

case $selection in
    "Install") main::install
    ;;
    "Remove ") main::remove
    ;;
    *) echo "Unknown"
    ;;
esac
