#!/usr/bin/env bash

# TODO: do everything as www-data user

OS_ERROR=3
INSTALL_ERROR=4

INSTALL_LOG=/tmp/usm-install.log

create_admin() {
    hashed_password=$(php -r "
        require('src/www/include/PasswordHash.php');
        \$hasher = new PasswordHash(8, False);
        echo \$hasher->HashPassword('$PASSWORD');
        unset(\$hasher);
    ")

    mysql -u root -e "\
        INSERT INTO usm.tblUsers (LOGIN, PASS, EMAIL, VALCODE, PERMISSIONS) \
        VALUES ('$USERNAME', '$hashed_password', '$(whoami)', '0', 127); \
    "
}

check_for_updates() {
    apt-get update
}

disable_prompts() {
    # disable interaction & mysql root password (local access only)
    export DEBIAN_FRONTEND=noninteractive
    debconf-set-selections <<< "mysql-server mysql-server/root_password password "
    debconf-set-selections <<< "mysql-server mysql-server/root_password_again password "

    # set postfix hostname, destinations, and mailer_type
    debconf-set-selections <<< "postfix postfix/destinations string ''"
    debconf-set-selections <<< "postfix postfix/mailname string $hostname"
    debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
}

determine_os() {
    if [[ -f /etc/lsb-release ]]; then
        . /etc/lsb-release
        OS=$DISTRIB_ID
        VERSION=$DISTRIB_RELEASE
    elif [[ -f /etc/debian_version ]]; then
        OS=Debian
        VERSION=$(cat /etc/debian_version)
    else
        echo "USM is only supported on Debian based systems"
        echo "    Run install.sh commands manually at your own risk"
        exit $OS_ERROR
    fi
}

install_dependencies() {
    PKGSTOINSTALL=''
    DEPENDENCIES=( \
		python-dev python3-dev python-paramiko \
        lighttpd php5-cgi \
        php5 php5-cli php5-gd php5-mysql \
        mysql-server unixodbc-dev libmyodbc \
        postfix \
		build-essential \
	)

    for DEPENDENCY in ${DEPENDENCIES[@]}
    do
        if [[ ! $(dpkg -s ${DEPENDENCY} > /dev/null 2>&1) ]]; then
            PKGSTOINSTALL=$PKGSTOINSTALL" "${DEPENDENCY}
        fi
    done

    apt-get --assume-yes install $PKGSTOINSTALL
    
    if [[ ! $? ]]; then
        exit $INSTALL_ERROR
    fi

    wget --quiet https://pyodbc.googlecode.com/files/pyodbc-3.0.7.zip &&
    unzip -qq pyodbc-3.0.7.zip &&
    cd pyodbc-3.0.7 &&
    python3 setup.py install
    cd .. &&
    rm pyodbc-3.0.7.zip
}

preconfigure_USM() {
    echo $hostname > /etc/hostname
    hostname $hostname
    sed -i "s/mydestination =/mydestination =#/g" /etc/postfix/main.cf
    service postfix restart

    mysql -u root < etc/mysql_create_db.txt
    create_admin

    cp etc/lighttpd.conf.example /etc/lighttpd/lighttpd.conf
    
    lighty-enable-mod fastcgi
    lighty-enable-mod fastcgi-php
    service lighttpd force-reload

    MULTIARCH=$(dpkg-architecture -qDEB_HOST_MULTIARCH)
    echo "[MySQL]
Description = MySQL driver
Driver = /usr/lib/${MULTIARCH}/odbc/libmyodbc.so
Setup = /usr/lib/${MULTIARCH}/odbc/libodbcmyS.so
UsageCount = 1" > /etc/odbcinst.ini

    mkdir /etc/usm
    cp --no-clobber etc/config.json.example /etc/usm/config.json
}

install_USM() {
    cp -rf src/www /var/.
    cp -rf src/usm /home/.

    chmod 777 /var/www/reportico/projects
    chmod 777 /var/www/reportico/projects/admin
    chmod 777 /var/www/reportico/templates_c
    chmod +x /var/www/command_processors/*.py
    chmod +x /var/www/*.py

    # TODO: move file to cron folder instead of global install - makes it easy to uninstall
    crontab etc/usm.cron
}

install() {
    determine_os

    echo "Please create your USM administration account"
    echo -n "Enter your username: "
    read USERNAME
    
    PASSWORD=''; check=''
    until [[ $PASSWORD == $check && $PASSWORD != '' ]]; do
        echo -n "Enter your password: "
        read -s PASSWORD
        echo
        if [[ $PASSWORD != '' ]]; then
            echo -n "Re-enter your password: "
            read -s check
            echo
            if [[ $PASSWORD != $check ]]; then
                echo "Password validation did not match"
            fi
        else
            echo "Your password cannot be left blank"
        fi
    done

    echo -n "Please enter your host name [example.com]: "
    read hostname

	echo "Checking for updates"
    check_for_updates >> $INSTALL_LOG 2>&1

    echo "Installing dependencies"
    echo "    Please be patient, this step can take a long time to complete..."
    disable_prompts >> $INSTALL_LOG 2>&1
    install_dependencies >> $INSTALL_LOG 2>&1

    echo "Preconfiguring USM"
    preconfigure_USM >> $INSTALL_LOG 2>&1

    echo "Installing USM"
    install_USM >> $INSTALL_LOG 2>&1

    echo "Configuration options can be modified with the following command:"
    echo "    sudo gedit /etc/usm/config.json"
}

remove() {
    # add warning that this deletes entire /var/www (or add usm sub-folder)
    crontab -r

    rm -rf /etc/usm
    rm -f /var/log/usm.log

    rm -rf /var/www
    rm -rf /home/usm
}

purge() {
    remove

    rm /etc/odbcinst.ini
}

case "$1" in
    install)
        install
        ;;
    remove)
        remove
        ;;
    *)
        echo "Usage: ./$0 [install|remove]"
        exit 1
esac