#!/bin/bash

standard=$1

help1="
You have to specify which webUi should be set to be standard and accessible on port 80.
"

help2="
The script takes only one argument which can be either 'new' or 'old'.
It will then set the standard webUi to new, or old respectively.
"

function testForConfigJson {
if [ ! -e /data/config.json ];then
cat >/data/config.json <<EOF
{
    "agg": {
        "address": "127.0.0.1",
        "subscriberPoolPort": 9008,
        "pubSub": 9009,
        "reqRep": 9010,
        "protocol": "tcp",
        "ipcSocketPath": "ipc:///tmp/ipc_sockets/"
    },
    "server": {
        "port": 80,
        "logLevel": "warn",
        "buildPath": "webApp/build",
        "binPath": "webApp/bin",
        "frontendDir": "webApp/bin"
    },
    "logger": {
        "verbose": true,
        "logLevel": "debug",
        "logFilePath": "/var/log/omgWebInterface"
    },
    "environment": "prod",
    "sudo": false
}
EOF
fi
}

function showFullHelp {
    echo "$help1$help2"
    exit;
}

function showHelp2 {
    echo "$help2"
    exit;
}

function stopUi {
    service omgWebInterface stop
    service httpd stop
}

function startUi {
    service omgWebInterface start
    service httpd start
}

if [[ "$standard" = "old" ]]; then
    stopUi
    testForConfigJson
    echo "Setting old webUi as standard on port 80"
    #set apache to port 80
    sed -i -e "s/Listen 8080/Listen 80/" /etc/httpd/conf/httpd.conf
    #set node to port 8080
    sed -i -e "s/: 80,/: 8080,/" /data/config.json
    startUi
elif [[ "$standard" = "new" ]]; then
    stopUi
    testForConfigJson
    echo "Setting new webUi as standard on port 80"
    #set apache to port 8080
    sed -i -e "s/Listen 80$/Listen 8080/" /etc/httpd/conf/httpd.conf
    # set node server to port 80
    sed -i -e "s/: 8080/: 80/" /data/config.json
    startUi

elif [[ "$standard" == "-h" ]]; then
    showHelp2

elif [[ "$standard" == "--help" ]]; then
    showHelp2

else
    echo -e "\e[31;1mUnknown argument!\e[0m"
    showFullHelp
fi
