#!/usr/bin/env bash

HOST=`hostname`


echo Examine domain settings of your server...

sed -i 's/verify_SSL\s=>\s1/verify_SSL => 0/g' /usr/libexec/webmin/asterisk/nginx_update/utils/letsencrypt/Crypt-LE/lib/Crypt/LE.pm

IP=`nslookup $HOST 8.8.8.8 | tail -n +3 | grep ^Address | awk '{print $2}'`

if [ "foo$IP" == "foo" ];then
    echo Domain $HOST is not defined - skip LetsEncrypt SSL certificate creation...
else
    echo Domain $HOST has A-record with ip address $IP
    if [ "`ip a | grep -c $IP`" != "0"  ]; then
        echo ip address $IP have found at your server - try to create LetsEncrypt SSL certificate...
        echo Configure LetsEncrypt SSL Certificate for $HOST
        res=`/usr/libexec/webmin/asterisk/domain.pl $HOST 2>&1`
        if [ "`echo $res | grep -c -i error`" != "0" ]; then
            echo Cannot configure LetsEncrypt SSL Certificate
        else
            echo Configure PBX Manager external ip address $IP
            /usr/libexec/webmin/asterisk/network.pl $IP 2>/dev/null
        fi 
    else
        echo "ip address $IP don't belong to your server - skip LetsEncrypt SSL certificate creation..."
    fi
fi

