#!/bin/bash
log=`mktemp`
code=0

which certbot > /dev/null 2>&1
if [ $? -eq 0 ]; then
    CERTBOT=`which certbot`
else
    CERTBOT=`which certbot-auto`
fi

#
# 証明書更新
#
for conf in `ls /etc/letsencrypt/renewal/`
do
    # ドメイン名取得
    domain=`echo ${conf}|sed -e 's/\([^ ]*\)\.conf/\1/p' -e d`

    # 認証方式取得
    authenticator=`grep authenticator /etc/letsencrypt/renewal/${conf}|awk '{print $3}'`

    if [ ${authenticator} = 'webroot' ]; then
        # Web認証の場合

        # ドキュメントルート取得
        webroot=`grep webroot_path /etc/letsencrypt/renewal/${conf}|grep =|awk '{print $3}'|awk -F '[,]' '{print $1}'`

        # 証明書更新
        ${CERTBOT} certonly --webroot \
        -w ${webroot} -d ${domain} --renew-by-default >> ${log} 2>&1
        [ $? -ne 0 ] && cat ${log}
    else
        # スタンドアロン認証の場合

        # 証明書更新
        lsof -i:80 > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            echo 'Webサーバー稼働中のためスタンドアロン認証不可'
        else
            ${CERTBOT} certonly -a standalone \
            -d ${domain} --renew-by-default >> ${log} 2>&1
            [ $? -ne 0 ] && cat ${log}
        fi
    fi
    
    # 古い証明書を削除
    find /etc/letsencrypt/archive/${domain}/ -mtime +30 -delete
    
done

#
# 証明書更新反映
#

# Webサーバー設定再読込み
lsof -i:443 > /dev/null 2>&1
if [ $? -eq 0 ]; then
    rpm -q systemd > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        systemctl reload httpd
    else
        /etc/rc.d/init.d/httpd reload > /dev/null 2>&1
    fi
fi

# SMTPサーバー設定再読込み
lsof -i:465 > /dev/null 2>&1
if [ $? -eq 0 ]; then
    rpm -q systemd > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        systemctl reload postfix
    else
        /etc/rc.d/init.d/postfix reload > /dev/null 2>&1
    fi
fi

# IMAPサーバー設定再読込み
lsof -i:995 > /dev/null 2>&1
if [ $? -eq 0 ]; then
    rpm -q systemd > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        systemctl reload dovecot
    else
        /etc/rc.d/init.d/dovecot reload > /dev/null 2>&1
    fi
fi

#
# ログをsyslogへ出力後削除
#
cat ${log}|logger -t `basename ${0}` ; rm -f ${log}