#!/bin/bash

set -e

# request certificates
while read -r domain
do
    if [ ! -d "/etc/letsencrypt/live/$domain" ]
    then
        certbot certonly --standalone        \
          -d "$domain"                       \
          --non-interactive                  \
          --agree-tos                        \
          --email micha@0rpheus.net          \
          --preferred-challenges=http        \
          --http-01-port=8888
    fi
done < /etc/haproxy/domains.txt

# renew all certificates
certbot renew --http-01-port=8888 --preferred-challenges=http

# 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