#!/bin/bash
set -e

# This is filled in when the packaging is built
OPENHIM_VERSION=

USERNAME=openhim
HOME=/home/$USERNAME
SH=/bin/bash
CONFIGDIR=/etc/openhim
CONFIGFILE=$CONFIGDIR/config.json

. /usr/share/debconf/confmodule
db_get openhim-core-js/watch-fs-for-cert
WATCH=$RET
if [ "$RET" = "true" ]; then
  db_get openhim-core-js/certPath
  CERT=$RET
  db_get openhim-core-js/keyPath
  KEY=$RET
fi

chown -R $USERNAME:$USERNAME $HOME/bin
chown -R $USERNAME:$USERNAME $HOME/bin/install_node.sh
chmod +x /usr/share/openhim-core/bin/openhim-core.js

# Fetch OpenHIM config file
mkdir /etc/openhim/ || true
if [ ! -f $CONFIGFILE ]; then
    echo "Fetching shiny new config file from github ..."
    wget -O $CONFIGFILE https://raw.githubusercontent.com/jembi/openhim-core-js/v$OPENHIM_VERSION/config/default.json
else
    echo "Config file "$CONFIGFILE" exits. Keeping old config, ensure you update this manually to support any new features in OpenHIM v"$OPENHIM_VERSION"!"
fi

if [ "$WATCH" = "true" ]; then
  sed -i -r '/watchFSForCert/s/false/true/' $CONFIGFILE
  sed -i -r '/certPath/s|/etc/letsencrypt/live/.*/cert.pem|'$CERT'|' $CONFIGFILE
  sed -i -r '/keyPath/s|/etc/letsencrypt/live/.*/privkey.pem|'$KEY'|' $CONFIGFILE
fi

cd $HOME

# Install node using nvm as openhim user
sudo -u $USERNAME $SH $HOME/bin/install_node.sh

# Ensure service is started
start openhim-core

echo "To configure your installation edit the config file at $CONFIGFILE"

exit 0
