#!/usr/bin/env bash

# certificates and key stores generated by this script
CERTIFICATES="/etc/hirs/certificates"

#################
# Key Generation
#################

# leave certificate directory intact on uninstall

#################
# ActiveMQ
#################

# no need to deconfigure, as it will be completely removed during uninstall

#################
# Tomcat
#################

if [[ $1 = "server" ]]; then
    # determine which version of tomcat is installed
    rpm -q tomcat6
    if [[ $? -eq 0 ]]; then
        TOMCAT_VERSION=`rpm -q --qf="%{VERSION}" tomcat6`
    else
        TOMCAT_VERSION=`rpm -q --qf="%{VERSION}" tomcat`
    fi

    TOMCAT_MAJOR_VERSION=`echo $TOMCAT_VERSION | head -c 1`

    if [[ $TOMCAT_MAJOR_VERSION = '6' ]]; then
        CATALINA_HOME=/usr/share/tomcat6
        TOMCAT_SERVICE=tomcat6
        TOMCAT_CONF=${CATALINA_HOME}/conf/tomcat6.conf
    elif [[ $TOMCAT_MAJOR_VERSION = '7' ]] ; then
        CATALINA_HOME=/usr/share/tomcat
        TOMCAT_SERVICE=tomcat
        TOMCAT_CONF=${CATALINA_HOME}/conf/tomcat.conf
    else
        echo "Unsupported Tomcat version: ${TOMCAT_MAJOR_VERSION}"
        exit 1
    fi

    if [[ -n `grep -o keystorePass $CATALINA_HOME/conf/server.xml` ]]; then
        SERVER_CONF=${CATALINA_HOME}/conf/server.xml
        TOMCAT_USERS=${CATALINA_HOME}/conf/tomcat-users.xml

        echo "Restoring $TOMCAT_CONF"
        sed -i "/^#begin-hirs-conf/,/^#end-hirs-conf/d" "$TOMCAT_CONF"

        echo "Restoring $SERVER_CONF"
        sed -i "s^<Connector port=\"8443\".*/></Service>^</Service>^" "$SERVER_CONF"

        echo "Restoring $TOMCAT_USERS"
        sed -i "s/<user username=\"tomcat\" password=\"tomcat\" roles=\"admin,admin-gui,manager,manager-gui.*<\/tomcat-users>/<\/tomcat-users>/" "$TOMCAT_USERS"
    fi
fi

#################
# Appraiser
#################

# no need to deconfigure, as it will be completely removed during uninstall

#################
# MySQL/MariaDB
#################

if [[ $1 = "server" ]]; then
    MYSQL_CERT_DIR=${CERTIFICATES}/mysql/

    if [[ -d $MYSQL_CERT_DIR ]]; then
        # stop the database
        if [[ $(rpm -qa mariadb*) ]]; then
            service mariadb stop
        else
            service mysqld stop
        fi

        rm -rf $MYSQL_CERT_DIR
        sed -i "/^#begin-hirs-conf/,/^#end-hirs-conf/d" /etc/my.cnf

        # start the database
        if [[ $(rpm -qa mariadb*) ]]; then
            service mariadb start
        else
            service mysqld start
        fi
    fi
fi