#!/bin/bash

## imunify email deploy script
# Short Description :Deploy Imunify Email 
# Description       :Installs Imunify Email Anti-Spam application
# Copyright         :Cloud Linux Zug GmbH
# License           :Cloud Linux Commercial License

readonly VERSION="beta.1"
readonly PACKAGE="imunifyemail"

readonly CENTOS_RELEASE_FILE=/etc/centos-release
readonly CLOUDLINUX_RELEASE_FILE=/etc/cloudlinux-release

readonly LOG_FILE=/var/log/imunifyemail-deploy.log
#readonly LOCK=/var/log/ie-deploy.lock

readonly CPANEL_INSTALL_DIR=/usr/local/cpanel
readonly CPANEL_BIN="$CPANEL_INSTALL_DIR/cpanel"

prepend_timestamp() {
    # Prepend current time to each line
    #
    # Usage: source-program | prepend_timestamp
    #
    # Note: it may fail if the input contains \0 bytes
    while IFS= read -r line
    do
        printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$line"
    done
}

log() {
    # Run given command and append its duplicated stdout/stderr to
    # $LOG_FILE.
    #
    # Usage: log <command> [<args>...]
    #
    "$@" |& prepend_timestamp | tee -a "$LOG_FILE"
    return "${PIPESTATUS[0]}"
}

exit_with_error() {
    log echo "$@"
    rm -rf "$lock"
    exit 1
}

print_debug_info() {
    if [ "$DEBUG" == "true" ]; then
        echo "$@"
    fi
}

check_panel() {
    if [ -f $CPANEL_BIN ]; then 
	log echo "cPanel: " `$CPANEL_BIN -V` 
    else 
	exit_with_error "Error during install: cPanel isn't detected $CPANEL_BIN"
    fi
}

check_os() {
    echo -n "Checking OS version ....."
    if [ -f $CENTOS_RELEASE_FILE ] ; then
        osfile=$CENTOS_RELEASE_FILE
        col=4
        os_id="CentOS" 
    elif [ -f $CLOUDLINUX_RELEASE_FILE ] ; then
        osfile=$CLOUDLINUX_RELEASE_FILE
        col=3
        os_id="CloudLinux"
    fi
    
    if [ -z `cat $osfile | awk "{ print \$$col }" | grep -e "^7" -e "^8" ` ] ; then
        echo -n "$os_id " 
        cat $osfile | awk "{ print \$$col }" 
    else
        exit_with_error "Wrong OS detected. Only CentOS 7,8 or CloudLinux 7,8 are supported"
    fi
}

check_exim() {
    if EXIM_BIN=`which exim 2>&1` ; then
       # log `exim --version`  # commented out for a while
       log echo $EXIM_BIN 
    else
        exit_with_error "No exim binary in PATH detected"
    fi
}

check_imunify() {
   if I360_BIN=`which imunify360-agent 2>&1` ; then 
      #I360_VER=`$I360_BIN version`
      log $I360_BIN version
      if [ -f /var/imunify360/license.json ] ; then
         chmod g+r /var/imunify360/license.json
      fi
   else
      exit_with_error "No Imunify 360 Agent found"
   fi
}

install_packages () {
    log echo "Installing packages"
    log yum install -y --enablerepo="epel" $PACKAGE
    log ie-config install
}

# Check prerequisites
# OS
check_os

# cPanel
check_panel

# Exim
check_exim

# Imunify 360
#check_imunify

# Check configurations Section

# Check SMTP ports are the open as non  privileged user - if there are open ports - warn user
# TODO add port checks


# Install RPMs
install_packages

