#!/usr/bin/env bash

# {{ ansible_managed }}

# Reload or restart nginx on a certificate state change

set -o nounset -o pipefail -o errexit

nginx_config="/etc/nginx/nginx.conf"
nginx_sites="/etc/nginx/sites-enabled"
nginx_action="{{ nginx_pki_hook_action }}"

# Check if current PKI realm is used by the 'nginx' webserver
certificate=$(grep -r "${PKI_SCRIPT_DEFAULT_CRT:-}" ${nginx_sites}/* || true)

# Get list of current realm states
read -r -a states <<< "$(echo "${PKI_SCRIPT_STATE:-}" | tr "," " ")"

if [ -n "${certificate}" ] && [[ ${states[*]} ]] ; then

    for state in "${states[@]}" ; do

        if [ "${state}" = "changed-certificate" ] || [ "${state}" = "changed-dhparam" ] ; then

            # Check if current init is systemd
            if pidof systemd > /dev/null 2>&1 ; then

                nginx_state="$(systemctl is-active nginx.service)"
                if [ "${nginx_state}" = "active" ] ; then
                    if /usr/sbin/nginx -c "${nginx_config}" -t > /dev/null 2>&1 ; then
                        systemctl "${nginx_action}" nginx.service
                    fi
                fi

            else

                nginx_pidfile="$(grep -E '^pid\s+' "${nginx_config}" | awk '{print $2}' | cut -d\; -f1)"
                if kill -0 "$(<"${nginx_pidfile}")" > /dev/null 2>&1 ; then
                    if /usr/sbin/nginx -c "${nginx_config}" -t > /dev/null 2>&1 ; then
                        /usr/sbin/service nginx "${nginx_action}" > /dev/null
                    fi
                fi

            fi

            break
        fi

    done

fi
