#!/bin/bash

echo "ACME.sh Manager"
sleep 1
echo "By Justman10000"
sleep 2.5

reset

note() {
    echo "BEWARE! Running webservers on port 80 must be deactivated"
    sleep 0.5
    echo "Note also, that the requested (sub) domain name must be pointing to the public IP of this system"
    sleep 1.5
}

command -v socat > /dev/null 2>&1 && apt install socat -y

# Possible values:
# Default: zerossl
## zerossl
## letsencrypt
## letsencrypttest
## sslcom
## google
## google_test
## actalis

#servers=(
#    zerossl
#    letsencrypt
#    letsencrypttest
#    buypass
#    buypasstest
#    sslcom
#    google
#    google_test
#)

server=letsencrypt

createDir() {
    ! [[ -d /etc/$server/live/${@}_ecc ]] && mkdir -p /etc/$server/live/${@}_ecc
}

unset LOG_LEVEL

case $1 in
    -i|--install)
        if [[ -d /root/.acme.sh ]]; then
            echo "ACME.sh is already installed"
            exit 1
        fi

        wget https://cdn.jsdelivr.net/gh/acmesh-official/acme.sh@master/acme.sh
#       for server in ${servers[@]}; do
            mkdir /etc/$server
            mkdir /etc/$server/live
#       done
        bash acme.sh --install
        ln -fs /root/.acme.sh /home/acme.sh
        exit
    ;;

    -u|--uninstall)
        rm -r /root/.acme.sh /home/acme.sh /etc/certs
    ;;

    -s|--standalone)
        note
        createDir $2
        bash /home/acme.sh/acme.sh --server $server --issue --domain $2 --standalone \
                     --cert-file /etc/$server/live/${2}_ecc/cert.pem \
                     --key-file /etc/$server/live/${2}_ecc/privkey.pem \
                     --fullchain-file /etc/$server/live/${2}_ecc/fullchain.pem
    ;;

    -w|--wildcard)
        note
        createDir $2
        bash /home/acme.sh/acme.sh --server $server --issue --domain *.$2 --dns --yes-I-know-dns-manual-mode-enough-go-ahead-please \
                     --cert-file /etc/$server/live/${2}_ecc/cert.pem \
                     --key-file /etc/$server/live/${2}_ecc/privkey.pem \
                     --fullchain-file /etc/$server/live/${2}_ecc/fullchain.pem
    ;;

    -r|--renew)
        note
        bash /home/acme.sh/acme.sh --server $server --renew --domain *.$2 --dns --yes-I-know-dns-manual-mode-enough-go-ahead-please
    ;;

    *)
        echo "Unknown argument"
        exit 1
    ;;
esac