#!/bin/bash

# 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

LONG_DATE=`date +%Y%m%d%H%M%S`

TOMCAT=tomcat9
TOMCAT_USER=tomcat
TOMCAT_HOME=/var/lib/${TOMCAT}
APACHE_CONF=/etc/apache2
SOURCE_DIR=/usr/share/dataone-cn-rest
SCRIPT_DIR=${SOURCE_DIR}/debian
JK_CONF=cn_jk.conf

db_get dataone-cn-os-core/cn.router.hostname
HOST_NAME=${RET}
KEY_DIR=/etc/letsencrypt/live/${HOST_NAME}
CERT_DIR=/etc/letsencrypt/live/${HOST_NAME}
D1_CONF=/etc/dataone
D1_HZ_PROCESS_PROPS="${D1_CONF}/cn/dataoneHazelcast.properties"
D1_LOG_DIR=/var/log/dataone
D1_LOG_FILE=dataone-cn-rest_service.install.log
###############################################################################
# Install CN war file
###############################################################################

# functions to echo to STDERR or the install log instead of STDOUT
logError () {
    log "ERROR $@" 
}

#####
##### log()
##### append stdout to a logfile
#####
function log() 
{
	#
	# Set Up logging
	# Reminder: don't echo to stdout, it messes up debconf
	#
    if [ ! -e ${D1_LOG_DIR} ]; then
        mkdir -p ${D1_LOG_DIR}
    fi
    chown -R ${TOMCAT_USER}:${TOMCAT_USER} ${D1_LOG_DIR}
    now=$(date "+%Y-%m-%d %H:%M:%S %Z: ")
    echo -e "${now} postinst $@" >> ${D1_LOG_DIR}/${D1_LOG_FILE}
}

## Stop tomcat
echo "Stopping Tomcat"
systemctl stop ${TOMCAT}

## backup the old war file
if [ -e ${TOMCAT_HOME}/webapps/cn.war ]
then
  echo "Backing up ${TOMCAT_HOME}/webapps/cn.war to ${TOMCAT_HOME}/webapps/cn.war.${LONG_DATE}"
  mv ${TOMCAT_HOME}/webapps/cn.war ${TOMCAT_HOME}/webapps/cn.war.${LONG_DATE}
fi  

## remove the cn application directory
if [ -d ${TOMCAT_HOME}/webapps/cn ]
then
  echo "Removing the old CN application directories"
  rm -rf ${TOMCAT_HOME}/webapps/cn
fi 

## copy the new war file into the webapps directory
echo copying new cn.war file to ${TOMCAT_HOME}/webapps/cn.war
cp ${SOURCE_DIR}/cn.war ${TOMCAT_HOME}/webapps/cn.war
chown -R ${TOMCAT_USER}:${TOMCAT_USER} ${TOMCAT_HOME}/webapps/cn.war

## expand the war file
CURR_DIR=`pwd`

## make cn directory and extract cn.war into it.
echo "Making cn application directory: ${TOMCAT_HOME}/webapps/cn"
mkdir ${TOMCAT_HOME}/webapps/cn
cd ${TOMCAT_HOME}/webapps/cn

echo "extracting cn.war into ${TOMCAT_HOME}/webapps/cn"
jar -xvf ${TOMCAT_HOME}/webapps/cn.war > /dev/null
chown -R ${TOMCAT_USER}:${TOMCAT_USER} ${TOMCAT_HOME}/webapps/cn
echo cd to $CURR_DIR
cd $CURR_DIR

################################################################################
# Configure hazelcast properties
################################################################################
# replace the IPs of the cn.iplist in node.properties so as to set them in hazelcast.xml
#CN_IPLIST=`egrep 'cn.iplist=' ${NODE_PROPS}  | awk 'BEGIN { FS = "=" } ; { print $2 }'`
# set the properties associated with this context
IPLIST_LABEL="cn.iplist"
IPLIST=""
if [ -e ${NODE_PROPS} ]; then
	# Fetch the context's ip list from the debconf database
	db_get dataone-cn-os-core/${IPLIST_LABEL}
	IPLIST=${RET}

else
	log "Couldn't set the IP list correctly."
	IPLIST="127.0.0.1"
fi

#add in commas
CN_IPLIST=${IPLIST// /, }

#place iplist value into dataoneHazelcast.properties at dataone.hazelcast.iplist
if ! (sed -i.bak "s/\(dataone\.hazelcast\.iplist *=\).*/\1${CN_IPLIST}/" ${D1_HZ_PROCESS_PROPS} >> ${D1_LOG_DIR}/${D1_LOG_FILE} 2>&1 ); then
      logError "Unable to modify iplist in ${D1_HZ_PROCESS_PROPS} with sed"
      exitWithFailureCode 9
fi


if ! (sed -i.bak "s/\(dataone\.hazelcast\.process\.clientiplist *=\).*/\1${CN_IPLIST}/" ${D1_HZ_PROCESS_PROPS} >> ${D1_LOG_DIR}/${D1_LOG_FILE} 2>&1 ); then
      logError "Unable to modify clientiplist in ${D1_HZ_PROCESS_PROPS} with sed"
      exitWithFailureCode 10
fi
###############################################################################
# Configure authentication
###############################################################################
## configure to use public cert and private key for token generation/verification
# get the private key
db_get dataone-cn-os-core/cn.server.privatekey.filename
KEY_FILENAME=${RET}
KEY_FILE=${KEY_DIR}'/'${KEY_FILENAME}

# get the cert
db_get dataone-cn-os-core/cn.server.publiccert.filename
SERVER_CERT_FILENAME=${RET}
PUBLIC_SERVER_CERT=${CERT_DIR}'/'${SERVER_CERT_FILENAME}

PUBLIC_SERVER_CERT_ESC=${PUBLIC_SERVER_CERT//\//\\\/}
KEY_FILE_ESC=${KEY_FILE//\//\\\/}
sed -i.bak --regexp-extended  "s/(cn\.server\.publiccert\.filename=).*/\1${PUBLIC_SERVER_CERT_ESC}/;" ${TOMCAT_HOME}/webapps/cn/WEB-INF/classes/org/dataone/configuration/portal.properties
sed -i.bak --regexp-extended  "s/(cn\.server\.privatekey\.filename=).*/\1${KEY_FILE_ESC}/;" ${TOMCAT_HOME}/webapps/cn/WEB-INF/classes/org/dataone/configuration/portal.properties


###############################################################################
# Configure Tomcat
###############################################################################

# Configure the context file
cp ${SCRIPT_DIR}/cn.xml ${TOMCAT_HOME}/conf/Catalina/localhost/
chown -R ${TOMCAT_USER}:${TOMCAT_USER} ${TOMCAT_HOME}/conf/Catalina/localhost/cn.xml
# Add permissions needed by cn
cp ${SCRIPT_DIR}/54cn.policy ${TOMCAT_HOME}/conf/policy.d/
chown -R ${TOMCAT_USER}:${TOMCAT_USER} ${TOMCAT_HOME}/conf/policy.d/54cn.policy


###############################################################################
# Configure Apache
###############################################################################

## Stop apache
echo "Stopping Apache"
/etc/init.d/apache2 stop

## copy in jk mount configuration file

if [ -e ${APACHE_CONF}/jk_mount/${JK_CONF} ]
then 
  JK_DIFF=`diff ${SCRIPT_DIR}/${JK_CONF} ${APACHE_CONF}/jk_mount/${JK_CONF}`
  if [ "${JK_DIFF}" != "" ]
  then
    echo "Backing up ${APACHE_CONF}/jk_mount/${JK_CONF} to ${APACHE_CONF}/jk_mount/${JK_CONF}.${LONG_DATE}"
    mv ${APACHE_CONF}/jk_mount/${JK_CONF} ${APACHE_CONF}/jk_mount/${JK_CONF}.${LONG_DATE}
  fi
fi
echo "Copying ${JK_CONF} site file to ${APACHE_CONF}/jk_mount/"
cp ${SCRIPT_DIR}/${JK_CONF} ${APACHE_CONF}/jk_mount/



###############################################################################
# Start Apache and Tomcat
###############################################################################

## Start Apache
/etc/init.d/apache2 start


## Start Tomcat
echo "starting Tomcat server"


systemctl start ${TOMCAT}


## Update DateONE Version Info Doc
java -jar /usr/share/dataone-cn-version-tool/dataone-cn-version-tool.jar -F/usr/share/dataone-cn-version-tool/version-tool.properties -html > /var/www/cn-version.html

db_stop
exit 0