#!/bin/bash

#
# AIM: Ask SSL certificates to an ACME Server
#

function updateCA()
{
    ca_location=$(CreoleGet eolesso_ca_location "")
    [[ -z ${ca_location} ]] && ca_location="/etc/ssl/local_ca"

    dst_root_x3=$(ls /etc/ssl/certs/DST_*.pem)
    [[ ! -d ${ca_location} ]] && mkdir -p ${ca_location}
    cp -rp /usr/share/ca-certificates/letsencrypt/*.crt ${ca_location}
    [[ ${?} -ne 0 ]] && echo "Warning : l'ajout de la CA Let's Encrypt pour eole-sso a échoué"

    cp -rp ${dst_root_x3} ${ca_location}
    [[ ${?} -ne 0 ]] && echo "Warning : l'ajout de la CA DST pour eole-sso a échoué"
}


if [[ $(CreoleGet cert_type non) == 'letsencrypt'  ]]
then
    if [[ $(CreoleGet activer_sso non) == 'local' ]]; then
        # Mise en place de la CA let's Encrypt
        updateCA
    fi

    cp -rp /usr/share/ca-certificates/letsencrypt/*.crt /usr/local/share/ca-certificates/
    update-ca-certificates > /dev/null 2>&1
    if [ -f /etc/ssl/letsencrypt/conf/live/$(CreoleGet nom_domaine_machine)/cert.pem ];
    then

        CONFDIR=$(CreoleGet le_config_dir)
        WOKRDIR=$(CreoleGet le_work_dir)
        LOGSDIR=$(CreoleGet le_logs_dir)
        iptables -I INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
        certbot --standalone  --config-dir ${CONFDIR} --work-dir ${WOKRDIR} --logs-dir ${LOGSDIR}   renew > /var/log/eole-letsencrypt-renew.log  2>&1
        iptables -D INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
    fi
    #We want to copy new certs to eole locations
    /usr/share/eole/letsencrypt/post.sh reconfigure

fi


exit 0
