#!/bin/bash
set -e

# This script is mentioned to be used for CommServer installation

PACKAGE="${1}"
START_TIME=$(date "+%Y-%m-%dT%H.%M.%S")
BACKUP_DIR="/root/backup/commserver/${START_TIME}"
INSTALLATION_DIR="/opt/remotenas/CommServer"
RPM_BACKUP_DIR="/root/server-versions"

init() {
	bold=$(tput bold)
	normal=$(tput sgr0)
	green=$(tput setaf 2)
	red=$(tput setaf 1)
}

green(){
	echo
	echo "${green}${bold}$@${normal}"
	echo
}

red(){
	echo
	echo "${red}${bold}$@${normal}"
	echo
}

verify_backup(){
    if [[ ! -d "${BACKUP_DIR}" ]]; then
        red "Backup directory doesn't exist"
        exit 1
    fi

    if diff -rq "${BACKUP_DIR/CommServer/}" "${INSTALLATION_DIR}/" > /dev/null; then
        red "Backup files count doesn't match server files count!"
        exit 1
    fi

    green "Backup performed successfully"
}

do_backup() {
    echo "Starting backup"
    mkdir -p "${BACKUP_DIR}"
    cp -a "${INSTALLATION_DIR}" "${BACKUP_DIR}/"
    verify_backup
}

uninstall_old_version(){
    rpm -e commserver
}

verify_package_exists(){
    if [[ ! -f "${PACKAGE}" ]]; then
        red "Package $PACKAGE doesn't exist"
        exit 1
    fi
}

verify_instalation(){
    status_code=$(curl -LI localhost:7004/rest/version -o /dev/null -w '%{http_code}' -s)

    if [[ ! "${status_code}" -eq 200 ]]; then
        red "FAILURE! Check version query returned status: ${status_code}"
        exit 1
    fi

    green "Installation successful"
}

backup_rpm(){
    if [[ ! -d "${RPM_BACKUP_DIR}" ]]
    then
        mkdir -p "${RPM_BACKUP_DIR}"
    fi

    cp "${PACKAGE}" "${RPM_BACKUP_DIR}/"
}

install(){
    echo "Starting installation..."
    rpm -ivh "${PACKAGE}"
    sleep 10
    verify_instalation
}

init
verify_package_exists
service commserver stop
do_backup
uninstall_old_version
install
backup_rpm