#!/usr/bin/with-contenv bashio
# ==============================================================================
# Start sshd service if enabled
# ==============================================================================
CERT_DIR=/data/letsencrypt
WORK_DIR=/data/workdir
PROVIDER_ARGUMENTS=()

EMAIL=$(bashio::config 'email')
DOMAINS=$(bashio::config 'domains')
KEYFILE=$(bashio::config 'keyfile')
CERTFILE=$(bashio::config 'certfile')
CHALLENGE=$(bashio::config 'challenge')
DNS_PROVIDER=$(bashio::config 'dns.provider')

if [ "${CHALLENGE}" == "dns" ]; then
    bashio::log.info "Selected DNS Provider: ${DNS_PROVIDER}"

    PROPAGATION_SECONDS=60
    if bashio::config.exists 'dns.propagation_seconds'; then
        PROPAGATION_SECONDS="$(bashio::config 'dns.propagation_seconds')" 
    fi
    bashio::log.info "Use propagation seconds: ${PROPAGATION_SECONDS}"
else
    bashio::log.info "Selected http verification"
fi

# AWS
if bashio::config.exists 'dns.aws_access_key_id' && bashio::config.exists 'dns.aws_secret_access_key'; then
    AWS_ACCESS_KEY_ID="$(bashio::config 'dns.aws_access_key_id')"
    AWS_SECRET_ACCESS_KEY="$(bashio::config 'dns.aws_secret_access_key')"

    export AWS_ACCESS_KEY_ID
    export AWS_SECRET_ACCESS_KEY
    PROVIDER_ARGUMENTS+=("--${DNS_PROVIDER}")
#Google
elif bashio::config.exists 'dns.google_creds'; then
    GOOGLE_CREDS="$(bashio::config 'dns.google_creds')"

    export GOOGLE_CREDS
    if [ -f "/share/${GOOGLE_CREDS}" ]; then
      cp -f "/share/${GOOGLE_CREDS}" "/data/${GOOGLE_CREDS}"
      chmod 600 "/data/${GOOGLE_CREDS}"
    else
      bashio::log.info "Google Credentials File doesnt exists in folder share."
    fi
    PROVIDER_ARGUMENTS+=("--${DNS_PROVIDER}" "--${DNS_PROVIDER}-credentials" "/data/${GOOGLE_CREDS}")

#Netcup
elif bashio::config.exists 'dns.netcup_customer_id' && bashio::config.exists 'dns.netcup_api_key' && bashio::config.exists 'dns.netcup_api_password'; then
    PROVIDER_ARGUMENTS+=("--authenticator" "certbot-dns-netcup:dns-netcup" "--certbot-dns-netcup:dns-netcup-credentials" /data/dnsapikey "--certbot-dns-netcup:dns-netcup-propagation-seconds" "${PROPAGATION_SECONDS}")

#TransIP
elif [ "${CHALLENGE}" == "dns" ] && [ "${DNS_PROVIDER}" == "dns-transip" ]; then
    bashio::config.require.username 'dns.transip_username'
    bashio::config.require 'dns.transip_api_key'
    if (( PROPAGATION_SECONDS < 240 )); then
        bashio::log.info "Increasing DNS propagation limit for TransIP to at least 240 seconds."
        PROPAGATION_SECONDS=240
    fi
    PROVIDER_ARGUMENTS+=("--authenticator" "certbot-${DNS_PROVIDER}:${DNS_PROVIDER}" "--certbot-${DNS_PROVIDER}:${DNS_PROVIDER}-credentials" /data/dnsapikey "--certbot-${DNS_PROVIDER}:${DNS_PROVIDER}-propagation-seconds" "${PROPAGATION_SECONDS}")

# CloudFlare
elif [ "${DNS_PROVIDER}" == "dns-cloudflare" ]; then
    if bashio::config.exists 'dns.cloudflare_api_token'; then
        bashio::log.info "Use CloudFlare token"
        echo "dns_cloudflare_api_token = $(bashio::config 'dns.cloudflare_api_token')" >> /data/dnsapikey
    else
        bashio::log.warning "Use CloudFlare global key (not recommended!)"
        echo -e "dns_cloudflare_email = $(bashio::config 'dns.cloudflare_email')\n" \
            "dns_cloudflare_api_key = $(bashio::config 'dns.cloudflare_api_key')\n" >> /data/dnsapikey
    fi

    PROVIDER_ARGUMENTS+=("--${DNS_PROVIDER}" "--${DNS_PROVIDER}-credentials" /data/dnsapikey "--dns-cloudflare-propagation-seconds" "${PROPAGATION_SECONDS}")

# DirectAdmin
elif [ "${CHALLENGE}" == "dns" ] && [ "${DNS_PROVIDER}" == "dns-directadmin" ]; then
    bashio::config.require 'dns.directadmin_url'
    bashio::config.require 'dns.directadmin_username'
    bashio::config.require 'dns.directadmin_password'
    PROVIDER_ARGUMENTS+=("--authenticator" "certbot-dns-directadmin:directadmin" "--certbot-dns-directadmin:directadmin-credentials" /data/dnsapikey "--certbot-dns-directadmin:directadmin-propagation-seconds" "${PROPAGATION_SECONDS}")

# Gandi
elif [ "${DNS_PROVIDER}" == "dns-gandi" ]; then
    if bashio::config.exists 'dns.gandi_sharing_id'; then
        bashio::log.info "Use Gandi sharing ID"
        echo "certbot_plugin_gandi:dns_sharing_id = $(bashio::config 'dns.gandi_sharing_id')" >> /data/dnsapikey
    fi
    PROVIDER_ARGUMENTS+=("--authenticator" "certbot-plugin-gandi:dns" "--certbot-plugin-gandi:dns-credentials" /data/dnsapikey)

#All others
else
    PROVIDER_ARGUMENTS+=("--${DNS_PROVIDER}" "--${DNS_PROVIDER}-credentials" /data/dnsapikey)
fi

# Gather all domains into a plaintext file
DOMAIN_ARR=()
for line in $DOMAINS; do
    DOMAIN_ARR+=(-d "$line")
done
echo "$DOMAINS" > /data/domains.gen

# Generate a new certificate if necessary or expand a previous certificate if domains has changed
if [ "$CHALLENGE" == "dns" ]; then
    certbot certonly --non-interactive --keep-until-expiring --expand \
        --email "$EMAIL" --agree-tos \
        --config-dir "$CERT_DIR" --work-dir "$WORK_DIR" \
        --preferred-challenges "$CHALLENGE" "${DOMAIN_ARR[@]}" "${PROVIDER_ARGUMENTS[@]}"
else
    certbot certonly --non-interactive --keep-until-expiring --expand \
        --email "$EMAIL" --agree-tos \
        --config-dir "$CERT_DIR" --work-dir "$WORK_DIR" \
        --preferred-challenges "$CHALLENGE" "${DOMAIN_ARR[@]}" --standalone
fi

# Get the last modified cert directory and copy the cert and private key to store
# shellcheck disable=SC2012
CERT_DIR_LATEST="$(ls -td $CERT_DIR/live/*/ | head -1)"
cp "${CERT_DIR_LATEST}privkey.pem" "/ssl/$KEYFILE"
cp "${CERT_DIR_LATEST}fullchain.pem" "/ssl/$CERTFILE"
