#!/bin/bash -e

SFTPGO_RELOAD=0
{% for service in ['ftpd','webdavd','httpd','telemetry'] %}
{% if sftpgo_conf[service].bindings.certificate_file is defined and sftpgo_conf[service].bindings.certificate_file is search('^letsencrypt:') %}
{% set certificate_name = sftpgo_conf[service].bindings.certificate_file | regex_replace('^letsencrypt:', '') %}
if [ $1 == "{{ certificate_name }}" ]; then
  SFTPGO_RELOAD=1
  cp /var/lib/dehydrated/certificates/certs/{{ certificate_name }}/fullchain.pem {{ sftpgo_root_dir }}/etc/ssl/{{ service }}.crt
  cp /var/lib/dehydrated/certificates/certs/{{ certificate_name }}/privkey.pem {{ sftpgo_root_dir }}/etc/ssl/{{ service }}.key
  chown root:{{ sftpgo_user }} {{ sftpgo_root_dir }}/etc/ssl/{{ service }}.{crt,key}
  chmod 644 {{ sftpgo_root_dir }}/etc/ssl/{{ service }}.crt
  chmod 640 {{ sftpgo_root_dir }}/etc/ssl/{{ service }}.key
fi
{% endif %}
{% endfor %}

if [ "$SFTPGO_RELOAD" == "1" ]; then
  systemctl reload sftpgo.service
fi
