#!/bin/bash
echo ""
echo ""
echo "================================================"
echo "|      __  _______  __  ___________________    |" 
echo "|     /  |/  / __ \/  |/  / ____/ ____/ __ )   |"
echo "|    / /|_/ / /_/ / /|_/ / __/ / __/ / __  |   |"
echo "|   / /  / / _, _/ /  / / /___/ /___/ /_/ /    |"
echo "|  /_/  /_/_/ |_/_/  /_/_____/_____/_____/     |"
echo "|                                              |"
echo "================================================"
echo ""
echo ""
                                         

#Creating needed folders and files if they don't already exist
if [ ! -d /config/.secrets ]
then
    mkdir /config/.secrets
fi

if [ ! -d /config/letsencrypt ]
then
    mkdir /config/letsencrypt
fi

if [ ! -f /config/.secrets/cloudflare.ini ]
then
    touch /config/.secrets/cloudflare.ini
fi

if [ ! -f /crontab.txt ]
then
    touch /crontab.txt
fi

if [ ! -s /config/.secrets/cloudflare.ini ]
then
    echo "cloudflare.ini is empty - please add your Cloudflare credentials or API key before continuing"

    exit 8
fi

#Securing cloudflare.ini to supress warnings
chmod 600 /config/.secrets/cloudflare.ini

#Outputting Environment Variables to /etc/environment for use by cron-based scripts
env >> /etc/environment

ln -s /config/letsencrypt /etc/letsencrypt

echo "Domains being added to the certificate are "$DOMAINS

echo "Propogation time is $PROPOGATION_TIME seconds"

echo "Creating certificates, or attempting to renew if they already exist"

if [[ $STAGING = true ]] 
then
    echo "Using staging endpoint - THIS SHOULD BE USED FOR TESTING ONLY"
    certbot certonly --staging --non-interactive --agree-tos --dns-cloudflare --dns-cloudflare-propagation-seconds $PROPOGATION_TIME --dns-cloudflare-credentials /config/.secrets/cloudflare.ini --email $EMAIL -d $DOMAINS
    echo "Creation/renewal attempt complete"
elif [[ $STAGING = false ]] 
then
    echo "Using production endpoint"
    certbot certonly --non-interactive --agree-tos --dns-cloudflare --dns-cloudflare-propagation-seconds $PROPOGATION_TIME --dns-cloudflare-credentials /config/.secrets/cloudflare.ini --email $EMAIL -d $DOMAINS
    echo "Creation/renewal attempt complete"
else
    echo "Unrecognised option for STAGING variable - check your configuration"

    exit 8
fi

echo "$INTERVAL /renew.sh > /proc/1/fd/1 2>/proc/1/fd/2" > /crontab.txt

echo "Starting automatic renewal job. Schedule is $INTERVAL"
crontab /crontab.txt

exec cron -f