#!/bin/sh

{% if fpbx_letsencrypt_cert is defined %}

if [ $1 == "{{ fpbx_letsencrypt_cert }}" ]; then
  cp /var/lib/dehydrated/certificates/certs/{{ fpbx_letsencrypt_cert }}/fullchain.pem /etc/asterisk/keys/{{ fpbx_letsencrypt_cert }}.crt
  cp /var/lib/dehydrated/certificates/certs/{{ fpbx_letsencrypt_cert }}/privkey.pem /etc/asterisk/keys/{{ fpbx_letsencrypt_cert }}.key
  chown asterisk:asterisk /etc/asterisk/keys/{{ fpbx_letsencrypt_cert }}.crt /etc/asterisk/keys/{{ fpbx_letsencrypt_cert }}.key
  chmod 600 /etc/asterisk/keys/{{ fpbx_letsencrypt_cert }}.crt /etc/asterisk/keys/{{ fpbx_letsencrypt_cert }}.key
  # Import cert into FreePBX if the certificate manager is installed
  if [ $(fwconsole list | grep -c certificates) == 1 ]; then
    fwconsole certificates --import
  fi
  asterisk -rx 'core restart gracefully'
fi

{% else %}

# No Let's Encrypt cert configured, nothing to do
exit 0

{% endif %}

