#!/usr/bin/env bash

SPATH="$(dirname "$(readlink -f ${BASH_SOURCE[0]})")"    # dir of the script
SNAME="$(basename ${BASH_SOURCE[0]})"                    # name of the script

ASCEDSCBDIR=$( dirname "$( readlink -f /usr/bin/asceds-certbot-gencert )" )
ASCEDSHOME="$( dirname ${ASCEDSCBDIR} )"
ASCEDSLIBDIR="$( dirname ${ASCEDSCBDIR} )"/lib
ASCEDSCONFDIR="$( dirname ${ASCEDSCBDIR} )"/etc
ASCEDSETCDIR="/etc/asceds"
ASCEDSCONF='local site hostconf certbot'
SERVICEDICT="port80-service-dict"
SERVICE_LOCK_FILE="${ASCEDSETCDIR}/.servPort80"

# get configuration
for CONFFILE in ${ASCEDSCONF} ; do 
   . ${ASCEDSCONFDIR}/asceds-${CONFFILE}.conf.proto
   if [ -r "${ASCEDSETCDIR}/asceds-${CONFFILE}.conf" ] ; then
      . ${ASCEDSETCDIR}/asceds-${CONFFILE}.conf
   fi
done

# load the functions
. ${ASCEDSLIBDIR}/asceds-utils

if ! PORT80PROC=$( ${ASCEDSCBDIR}/test80 ) ; then
   echo "Could not determine port 80 listener" >&2
   if [ -n "${ALARMSEND}" ] ; then
      asceds-mailto-alarm "Standalone host $( hostname -f ) cannot find port 80 process" \
                          "${ASCEDSLOGF}"
   fi
   exit 1
fi

if [ -z "${PORT80PROC}" ] ; then 
   exit 0
fi

if [ ! -r "${ASCEDSETCDIR}/${SERVICEDICT}" ] ; then
   if [ -r "${ASCEDSCONFDIR}/${SERVICEDICT}.proto" ] ; then
      /bin/cp "${ASCEDSCONFDIR}/${SERVICEDICT}.proto" "${ASCEDSETCDIR}/${SERVICEDICT}"
   elif [ -r "${ASCEDSCONFDIR}/${SERVICEDICT}" ] ; then
      /bin/cp "${ASCEDSCONFDIR}/${SERVICEDICT}" "${ASCEDSETCDIR}/${SERVICEDICT}"
   else
      asceds-mailto-alarm "Standalone host $( hostname -f ) no port 80 process mapping to service" \
                       "${ASCEDSLOGF}"
      exit 1
   fi
fi


while IFS= read -r line; do
    [[ -z $line || $line =~ ^[[:space:]]*# ]] && continue

    read -r P80_PROC P80_SERV <<< "$line"

    if [[ ${P80_PROC} == "${PORT80PROC}" ]]; then
        printf '%s\n' "$P80_SERV" > "${SERVICE_LOCK_FILE}"
        systemctl stop "${P80_SERV}"
        exit
    fi
done < "${ASCEDSETCDIR}/${SERVICEDICT}"

echo "No service listed for the port 80 listener" >&2
if [ -n "${ALARMSEND}" ] ; then
   asceds-mailto-alarm "Standalone host $( hostname -f ) no port listed for the port 80 process" \
                       "${ASCEDSLOGF}"
fi
exit 1



