#!/bin/bash

COLOR_NONE='\033[0m'
COLOR_BOLD='\033[1m'
COLOR_BLUE='\033[0;34m'
COLOR_BOLD_BLUE='\033[1;34m'
COLOR_GREEN='\033[0;32m'
COLOR_BOLD_GREEN='\033[1;32m'
COLOR_YELLOW='\033[0;33m'
COLOR_BOLD_YELLOW='\033[1;33m'
COLOR_RED='\033[0;31m'
COLOR_BOLD_RED='\033[1;31m'

echoinfo() {
    printf "${COLOR_BOLD_BLUE}INFO:${COLOR_NONE} %s\n" "$1"
}

echowarn() {
    printf "${COLOR_BOLD_YELLOW}WARNING:${COLOR_YELLOW} %s${COLOR_NONE}\n" "$1"
}

echoerr() {
    printf "${COLOR_BOLD_RED}ERROR:${COLOR_RED} %s${COLOR_NONE}\n" "$1"
}

# Test that we have a compatible shell
if ! [[ $(echo test) ]]; then
    printf "${COLOR_BOLD_RED}This shell isn't compatible with this script.\n"
    printf "${COLOR_RED}Try running this script as %s${COLOR_NONE}\n" "/bin/bash $0"
    exit 1
fi


OUR_LOCATION="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
RES="$OUR_LOCATION/res"

SERVICE_NAME="gamepaneliod"

FILE_PASSWD_LOCATION="/usr/sbin/gamepanelio-passwd"

LIBS_DIR="/usr/lib/${SERVICE_NAME}/"
LOGS_DIR="/var/log/${SERVICE_NAME}/"
CONF_DIR="/etc/${SERVICE_NAME}/"

SERVICE_SYSD_FILE="/lib/systemd/system/${SERVICE_NAME}.service"
SERVICE_SYSV_FILE="/etc/init.d/${SERVICE_NAME}"

JAVA_BIN="/usr/bin/java"

SYSTEMD_DIR="/usr/lib/systemd"
SYSV_DIR="/etc/init.d"
USE_SYSTEMD=0
USE_SYSV=0

SUDOERS_D_DIR="/etc/sudoers.d/"

PROPS_FILE="${CONF_DIR}config/prod/environment.properties"

if [[ $EUID -ne 0 ]]; then
   echoerr "This script must be run as root"
   exit 1
fi

echoinfo "Preparing system..."

if [ -d "$LIBS_DIR" ]; then
    echoerr "System already has gamepaneliod installed."
    exit 1
fi

CSD_LIBS="/usr/lib/craftsrvd/"
CSD_ETC="/etc/craftsrvd/"
CSD_SYSD="/lib/systemd/system/craftsrvd.service"
CSD_SYSV="/etc/init.d/craftsrvd"
CSD_PASSWD="/usr/sbin/craftsrv-passwd"
CSD_SUDO="$SUDOERS_D_DIR/craftsrvd"
CSD_HOME="/home/cratsrvd"
if [ -d "$CSD_LIBS" -o -d "$CSD_ETC" ]; then
    echoinfo "Found existing CraftSRVd installation. Converting to gamepaneliod."

    if [[ `systemctl` =~ -\.mount ]]; then
        systemctl stop craftsrvd
    elif [ -d "$SYSV_DIR" ]; then
        service craftsrvd stop
    else
        echoerr "Couldn't find systemd or sysv."
        exit 1
    fi

    if [ -d "$CSD_LIBS" ]; then
        mv "$CSD_LIBS" "$LIBS_DIR"
    fi

    if [ -d "$CSD_ETC" ]; then
        mv "$CSD_ETC" "$CONF_DIR"
    fi

    if [ -f "$CSD_SYSD" ]; then
        mv "$CSD_SYSD" "$SERVICE_SYSD_FILE"
    fi

    if [ -f "$CSD_SYSV" ]; then
        mv "$CSD_SYSV" "$SERVICE_SYSV_FILE"
    fi

    if [ -f "$CSD_PASSWD" ]; then
        mv "$CSD_PASSWD" "$FILE_PASSWD_LOCATION"
    fi

    if [ -f "$CSD_SUDO" ]; then
        mv "$CSD_SUDO" "$SUDOERS_D_DIR/$SERVICE_NAME"
    fi

    if [ -d "$CSD_HOME" ]; then
        mv "$CSD_HOME" "/home/gamepaneliod"
    fi

    usermod -l gamepaneliod craftsrvd -d /home/gamepaneliod

    groupmod -n gamepaneliod craftsrvd
    groupmod -n gamepanelio craftsrv
fi

if ! type "$JAVA_BIN" > /dev/null; then
    echoerr "Looks like we can't find Java installed at /bin/java ?"
    exit 1
fi

if ! type "tar" > /dev/null; then
    echo "You need to install tar first, so we can extract the files."
    exit 1
fi

if ! type "sudo" > /dev/null; then
    echoerr "The system needs sudo installed, so that the daemon can delegate commands."
    exit 1
fi

if ! type "softlimit" > /dev/null; then
    echoerr "Make sure you have the softlimit command installed via the daemontools package."
    exit 1
fi

if ! [ -f "$RES/lib.tar.gz" ]; then
    echoerr "No libs archive found."
    exit 1
fi

if ! [ -d "$SUDOERS_D_DIR" ]; then
    echoerr "Your system isn't configured to enable /etc/sudoers.d/"
    exit 1
fi

if [[ `systemctl` =~ -\.mount ]]; then
    echoinfo "Found sysyemd"
    USE_SYSTEMD=1
elif [ -d "$SYSV_DIR" ]; then
    echoinfo "Found sysv"
    USE_SYSV=1
else
    echoerr "Couldn't find systemd or sysv."
    exit 1
fi


echoinfo "Creating daemon user: gamepaneliod"

useradd -r gamepaneliod


echoinfo "Creating user group: gamepanelio"

groupadd gamepanelio


echoinfo "Creating directories"

mkdir -p "$LIBS_DIR"
mkdir -p "$LOGS_DIR"
mkdir -p "$CONF_DIR"

chown gamepaneliod:gamepaneliod "$LOGS_DIR"
chown gamepaneliod:gamepaneliod "$CONF_DIR"


echoinfo "Installing libraries"

if ! tar -xf "$RES/lib.tar.gz" -C "$LIBS_DIR"; then
    echoerr "There was a problem extracting the libraries"
    exit 1
fi


echoinfo "Installing daemon scripts"

if [ $USE_SYSTEMD == 1 ]; then
    cp "$RES/services/${SERVICE_NAME}.service" "$SERVICE_SYSD_FILE"
    chmod 755 "$SERVICE_SYSD_FILE"

    systemctl enable "$SERVICE_NAME"
else
    cp "$RES/services/${SERVICE_NAME}" "$SERVICE_SYSV_FILE"
    chmod 755 "$SERVICE_SYSV_FILE"

    if type "chkconfig" &> /dev/null; then
        chkconfig "$SERVICE_NAME" on
    elif type "update-rc.d" &> /dev/null; then
        update-rc.d "$SERVICE_NAME" defaults
    else
        echowarn "Couldn't configure the daemon for start on system boot! You may want to configure this!"
    fi
fi

cp "$RES/sbin/gamepanelio-passwd" "$FILE_PASSWD_LOCATION"
chmod 755 "$FILE_PASSWD_LOCATION"


echoinfo "Configuring sudo"

DEST="$SUDOERS_D_DIR/$SERVICE_NAME"
cp "$RES/sudoers.d/$SERVICE_NAME" "$DEST"
chmod 440 "$DEST"


echoinfo "Starting daemon"

if [ $USE_SYSTEMD == 1 ]; then
    systemctl start "$SERVICE_NAME"
else
    service "$SERVICE_NAME" start
fi

# Wait up to 10 seconds for the authentication key to be generated, then echo it to screen
for counter in {1..100}
do
    if [ -f $PROPS_FILE ]; then
        AUTHKEY="$(sed -n -e 's/^.*authentication.key=//p' ${PROPS_FILE})"

        if ! [[ -z "${AUTHKEY// }" ]]; then
            printf "${COLOR_BOLD_BLUE}INFO:${COLOR_NONE} Your daemon authentication key is: ${COLOR_BOLD}${AUTHKEY}${COLOR_NONE}\n"
            break
        fi
    fi

    sleep 0.1
done

if [ $counter == 100 ]; then
    echowarn "We couldn't get the daemon authentication key for you."
    echowarn "Something might have gone wrong when starting the daemon?.. Or we didn't wait long enough..."
fi

echo
printf "${COLOR_GREEN}\342\234\224 All done!${COLOR_NONE}\n"

exit 0