#!/bin/bash

H_NAME=$( hostname -f )
LE_SERVICES_SCRIPT_DIR=/usr/lib/acme/hooks
LE_CERTS_DIR=/var/lib/acme/live/$H_NAME
LE_LOG_DIR=/var/log/letsencrypt
POSTGRESQL_CERTDIR=/etc/pki/postgresql
POSTGRESQL_KEYFILE=$POSTGRESQL_CERTDIR/postgresql.key
DATE=$( date )
RETVAL=

[ ! -d $POSTGRESQL_CERTDIR ] && mkdir -p $POSTGRESQL_CERTDIR
[ ! -d $LE_LOG_DIR ] && mkdir $LE_LOG_DIR
echo "$DATE" >> $LE_LOG_DIR/postgresql.log

logger "acme-pg-hook: Check if the certificate has been renewed"
cmp ${LE_CERTS_DIR}/privkey  ${POSTGRESQL_KEYFILE}
RETVAL=$?
if [ $RETVAL -eq 0 ] ; then
    logger "acme-pg-hook: No new cerficate."
    echo "acme-pg-hook: No new cerficate." >> $LE_LOG_DIR/postgresql.log
else
    logger "acme-pg-hook: Copying the key file"
    echo "Copy the key file" >> $LE_LOG_DIR/postgresql.log
    /bin/cp -f ${LE_CERTS_DIR}/privkey  ${POSTGRESQL_KEYFILE}
fi

chmod 440 ${POSTGRESQL_KEYFILE}
chown root ${POSTGRESQL_KEYFILE}
chgrp postgres ${POSTGRESQL_KEYFILE}

if [ -x /bin/systemctl ] ; then
    logger "acme-pg-hook: Reload the postgresql service after a certificate renewal"
{% if ansible_distribution_file_variety == "Debian" %}
    systemctl reload postgresql >> $LE_LOG_DIR/postgresql.log 2>&1
{% else %}
    systemctl reload postgresql-{{ psql_version }} >> $LE_LOG_DIR/postgresql.log 2>&1
{% endif %}
    echo "acme-pg-hook: Reload the postgresql service" >> $LE_LOG_DIR/postgresql.log
else
    logger "acme-pg-hook: Restart the postgresql service after a certificate renewal"
    echo "Restart the postgresql service" >> $LE_LOG_DIR/postgresql.log
    service postgresql restart >> $LE_LOG_DIR/postgresql.log 2>&1
fi

logger "acme-pg-hook: Done"
echo "acme-pg-hook: Done." >> $LE_LOG_DIR/postgresql.log

exit 0