#!/bin/bash

set -e

ACTION=${1}
NEW_VERSION=${2}


TOMCAT=tomcat9
TOMCAT_USER=tomcat
DATAONE_USER=tomcat
TOMCAT_HOME=/var/lib/tomcat9
SOURCE_DIR=/usr/share/dataone-cn-os-core
SCRIPT_DIR=${SOURCE_DIR}/debian
APACHE_CONF=/etc/apache2
MOD_JK_CONF=/etc/libapache2-mod-jk
SITES="cn-ssl"

# Source the debconf library
if [ -e "/usr/share/debconf/confmodule" ]; then
    . /usr/share/debconf/confmodule
else
    echo "debconf must be installed. Exiting."
    exit 1
fi

# Reminder: don't echo to stdout, it messes up debconf

D1_LOG_DIR=/var/log/dataone
D1_LOG_FILE=dataone-cn-os-core.remove.log
if [ ! -e ${D1_LOG_DIR} ]; then
    mkdir -p ${D1_LOG_DIR}
    chown ${TOMCAT_USER}:${TOMCAT_USER} ${D1_LOG_DIR}
fi

# functions to echo to STDERR or the install log instead of STDOUT
logError () {
    echo -e "$@" 1>&2
}

log () {
    now=$(date "+%Y-%m-%d %H:%M:%S %Z: ")
    echo -e "${now} prerm $@" >> ${D1_LOG_DIR}/${D1_LOG_FILE}
}
LONG_DATE=`date +%Y%m%d%H%M%S`

log "$ACTION $VERSION"

####
#### Unfortunately, this will not work with ansible.
#### We should have an ansible_seen or ansible_set flag in addition
#### to the seen flag such that when prerm is run
#### ansible_seen = true & seen == true will result in  
#### ansible_seen = false &  seen == true; while
#### ansible_seen = false & seen == true will result in  
#### ansible_seen = false & seen == false.
#### 
#### using a separate indicator will allow for the postinst
#### script to know whether ansible has modified the 
#### template questions before an upgrade or whether the upgrade
#### was kicked off on command line by apt-get or some other debian
#### package management
####
#### But for now, prerm will do nothing and postinst will set
#### seen to false after it is complete.
#### if seen is still false when postinst runs again,
#### then postinst will assume that ansible is not controlling the install
####
#declare -a DEBCONF=(`debconf-show dataone-cn-os-core | awk 'BEGIN { FS = "[: ]" } ; { print $2 }'`)
#for template_name in ${DEBCONF[@]}
#do
	# once you configure a CN as the first LDAP CN, do not reconfigure
#	if [ "$template_name" != "dataone-cn-os-core/cn.openldap.firstcn" ]; then
#		db_fset $template_name seen false
#	fi
#done
#

db_stop
log "Removal of CN OS CORE complete."

exit 0
