#!/bin/bash
set -e

# This script is mentioned to be used ONLY for the first REL05 installation.
# Using this script avoids RPM conflict: when AS was already manually installed
#in correct dir and RPM tried to replace files.

# For further developments (with AS already installed via RPM) new script should
#be created.

PACKAGE="${1}"
START_TIME=$(date "+%Y-%m-%d_%H.%M.%S")
BACKUP_DIR="/root/backup/tomcat/${START_TIME}"
TOMCAT_LINK="/usr/share/tomcat/webapps/app"
WEBAPPS_INSTALLATION_DIR="/opt/remotenas/AppServer/tomcat/webapps"
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/webapps}" "${WEBAPPS_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 "${WEBAPPS_INSTALLATION_DIR}" "${BACKUP_DIR}/"
    verify_backup
}

remove_redundant_files(){

    echo "Removing old server installation"

    # you'll probably ask why - during first installation from RPM old server files (like libs
    # or compiled classes) must be removed, because rpm will cause conflict when replacing files
    # or will leave old files (like old libs) unmodified, what would trigger incorrect server state

    rm -rf "${WEBAPPS_INSTALLATION_DIR}"
    rm -f "${TOMCAT_LINK}"

    if [[ -d "${WEBAPPS_INSTALLATION_DIR}" ]]; then
        red "${WEBAPPS_INSTALLATION_DIR} still exists!"
        exit 1
    fi

    if [[ -f "${TOMCAT_LINK}" ]]; then
        red "${TOMCAT_LINK} still exists!"
        exit 1
    fi
}

verify_package_exists(){
    if [[ -z "${PACKAGE}" ]]; then
        red "You must provide package path as parameter"
    fi

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

verify_instalation(){
    status_code=$(curl -LI localhost:8080/app/hm/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 5
    verify_instalation
}

init
verify_package_exists
service tomcat stop
do_backup
remove_redundant_files
install
backup_rpm