#!/bin/bash

set -e

# request certificates
while read -r domain
do
    if [ ! -d "/etc/letsencrypt/live/$domain" ]
    then
        certbot certonly                     \
          -d "$domain"                       \
          --non-interactive                  \
          --agree-tos                        \
          --email micha@0rpheus.net          \
          --rsa-key-size 4096                \
          --webroot                          \
          --webroot-path /var/www/html
    fi
done < /etc/haproxy/all-domains.txt

# renew all certificates
certbot renew                     \
    --rsa-key-size 4096           \
    --webroot                     \
    --webroot-path /var/www/html

# copy certificates
find /etc/letsencrypt/live/ -mindepth 1 -maxdepth 1 -type d | while read -r domain_path
do
    domain=$(basename "$domain_path")

    if grep -q "$domain" /etc/haproxy/domains.txt
    then
        pem_file=/etc/haproxy/certs/$domain.pem
        cat "$domain_path/fullchain.pem" "$domain_path/privkey.pem" > "$pem_file"
        chmod 600 "$pem_file"
    fi
done

systemctl reload haproxy
/usr/local/bin/ocsp_update.sh

# prosody cert
prosodyctl --root cert import /etc/letsencrypt/live
systemctl restart prosody.service