#!/bin/ash

self=$0
create=false
request=false

show_help () {
    cat <<END_HELP
Usage: $self [-c] [-r] <Domain name>

Options:
    -c,    Will create nginx config for domain
    -r,    Will request ssl for domain

END_HELP
}

while getopts crh opt; do
    case $opt in
        c) create=true ;;
        r) request=true ;;
        h) show_help
           exit ;;
        *) echo 'Error in parsing options' >&2
           exit 1
    esac
done

shift "$(( OPTIND - 1 ))"
for domain do
    domain=$domain
done

#if no flags given quit with help promt
if ! $create && ! $request; then
    echo "No option set"
    show_help
    exit 1
fi

#if only request test if domain exists
if ! $create && $request; then
    if ! test -f /etc/nginx/sites-enabled/"$domain" ; then
    echo 'Domain does not exist yet, please create it using the `-c` option'
    show_help
    exit 1
    fi
fi

if $create; then
    mkdir -p /etc/acmesh/inst/$domain
    cp /etc/nginx/sites-available/nginx_template_nossl /etc/nginx/sites-available/"$domain"_nossl
    sed -i -e 's/DOMAINname/'$domain'/g' /etc/nginx/sites-available/"$domain"_nossl
    cp /etc/nginx/sites-available/nginx_template_ssl /etc/nginx/sites-available/"$domain"_ssl
    sed -i -e 's/DOMAINname/'$domain'/g' /etc/nginx/sites-available/"$domain"_ssl
    ln -s /etc/nginx/sites-available/"$domain"_nossl /etc/nginx/sites-enabled/"$domain"
    service nginx reload
fi

if $request; then
    #Backing-up and removing current config
    sed -n '/#beginConf/,/#endConf/p' /etc/nginx/sites-available/"$domain"_nossl > /tmp/"$domain"-config
    sed -n -i '/#beginConf/{:a;N;/#endConf/!ba;N;s/.*\n/#ConfHere\n/};p' /etc/nginx/sites-available/"$domain"_nossl
    service nginx reload

    #Enabling SSL
    /opt/acmesh/acme.sh --config-home '/etc/acmesh/data' --issue --nginx --ocsp --keylength 'ec-384' -d "$domain"
    certsatus=$?
    
    if test $certsatus -eq 0
    then
        site_ext="ssl"
        mkdir -p /etc/acmesh/inst/$domain
        /opt/acmesh/acme.sh  --config-home '/etc/acmesh/data' --install-cert --ecc --domain $domain --cert-file /etc/acmesh/inst/$domain/cert.pem --key-file /etc/acmesh/inst/$domain/key.pem --ca-file /etc/acmesh/inst/$domain/ca.cer --fullchain-file /etc/acmesh/inst/$domain/fullchain.pem --reloadcmd 'service nginx reload'
    else
        site_ext="nossl"
        rm -rf /etc/acmesh/certs/$domain*
        echo "LE failed, restoring configuration"
    fi
    unset certsatus

    #Restoring config
    sed -i -e "1,/^#ConfHere/s/\(^#Conf.*\)/#ConfHere1 /" -e "/#ConfHere1/ r /tmp/"$domain"-config" -e '/#ConfHere/c\' /etc/nginx/sites-available/"$domain"_"$site_ext"


    rm /etc/nginx/sites-enabled/"$domain"
    ln -s /etc/nginx/sites-available/"$domain"_"$site_ext" /etc/nginx/sites-enabled/"$domain"
    service nginx reload
fi
   