#!/bin/bash

checkCredentials(){
   #checks the current user which executes the script
    if [ "$EUID" -ne 0 ];
      then echo "Please run this installer as root, otherwise the process can't be started."
      exit
    else
      enableTOAREPO
    fi
}

enableTOAREPO() {
    echo "### check if required repository is enabled"

    #checks if the justin repo is enabled otherwise it will be enabled and then executes the next steps
    if yum repolist -v toa-justin |grep "Repo-status"|cut -d ":" -f2-|awk '{ sub(/^[ \t]+/, ""); print }'| grep -q 'enabled'; then
      installDependenciesForUI
      installUserInterface
    else
      #sets the toa-justin repo
      echo "[toa]
            name=TOA
            baseurl=https://packages.toolsonair.com/toarepo
            gpgcheck=0
            skip_if_unavailable=1
            keepcache=0
            sslverify=0
            enabled=0

            [toa-local]
            name=TOA-local
            baseurl=file:///opt/toarepo
            gpgcheck=0
            skip_if_unavailable=1
            keepcache=0
            enabled=0

            [toa-justin]
            name=TOA-justin
            baseurl=https://packages.toolsonair.com/justin
            gpgcheck=0
            sslverify=0
            skip_if_unavailable=1
            keepcache=0
            enabled=1

            [toa-juststore]
            name=TOA-juststore
            baseurl=https://packages.toolsonair.com/juststore
            gpgcheck=0
            skip_if_unavailable=1
            keepcache=0
            sslverify=0
            enabled=0

            [toa-recap]
            name=TOA-recap
            baseurl=https://packages.toolsonair.com/recap
            gpgcheck=0
            sslverify=0
            skip_if_unavailable=1
            keepcache=0
            enabled=0
      " > /etc/yum.repos.d/toa.repo

      enableTOAREPO
    fi
}

installDependenciesForUI(){
    echo ""
    echo "### install dependencies"
    #python3 is required for the network bandwidth management, java for the backend and httpd for the user interface
    yum install -y -q httpd java ipmitool python3 python3-libs python3-pip python3-setuptools python36-chardet python36-lxml python3-devel mod_ssl --enablerepo="toa-justin"
    #install the bandwidth management tool
    pip3 install tcconfig >> /dev/null
}

installUserInterface(){
    echo ""
    echo "### install user interface"
    #install user interface and backend
    yum install -y -q toa-justin-software --enablerepo="toa-justin"

    #enables the required ports
    firewall-cmd --zone=public --permanent --add-port=80/tcp >> /dev/null
    firewall-cmd --zone=public --permanent --add-port=443/tcp >> /dev/null
    firewall-cmd --zone=public --permanent --add-port=8080/tcp >> /dev/null
    firewall-cmd --zone=public --permanent --add-port=8081/tcp >> /dev/null
}


checkCredentials
