#!/usr/bin/env bash

# Domain specifies the site for withc you download the certs
DOMAIN="site.example.com"

# Bucket is the source for the cert
BUCKET="https://minio.example.com/certs"

# Service is the service that needs to be restarted for nginx apache2 postfix ... this script works out of the box
# for other services the download path must be changed acordingly.
# std for my preferred setup is the certs for the service is in a ssl folder in the config dir for the service
SERVICE="nginx"

# wait as the cron.daily is run on all hosts at the same time so get it run randomly run in 30 seconds
MAXWAIT=30

# Put this in crontab for every 12 hours
# Assuming Apache, and that your private key and certificate are located in
# - /etc/apache2/privkey.pem
# - /etc/apache2/fullchain.pem , respectively

#set -euf -o pipefail

sleep $((RANDOM % MAXWAIT))

# Create teh needed Directory in the Service Config Directory
mkdir -p /etc/$SERVICE/ssl

# Download the latest certificate to a temporarily location so we can check validity
curl -s -o /etc/$SERVICE/ssl/$DOMAIN.fullchain $BUCKET/$DOMAIN.fullchain
curl -s -o /etc/$SERVICE/ssl/$DOMAIN.chain $BUCKET/$DOMAIN.chain
curl -s -o /etc/$SERVICE/ssl/$DOMAIN.crt $BUCKET/$DOMAIN.crt
curl -s -o /etc/$SERVICE/ssl/$DOMAIN.key $BUCKET/$DOMAIN.key
curl -s -o /etc/$SERVICE/ssl/$DOMAIN.pem $BUCKET/$DOMAIN.pem
curl -s -o /etc/$SERVICE/ssl/$DOMAIN.pfx $BUCKET/$DOMAIN.pfx


# Verify the certificate is valid for our existing key (should be)
MOD_CRT=`openssl x509 -modulus -noout -in /etc/$SERVICE/ssl/$DOMAIN.crt | openssl md5`
MOD_KEY=`openssl rsa -modulus -noout -in /etc/$SERVICE/ssl/$DOMAIN.key | openssl md5`
if [ "$MOD_CRT" != "$MOD_KEY" ]; then
  echo "Key didn't match: $MOD_CRT vs $MOD_KEY"
  #exit 1
fi

# Deploy the certificate and graceful reload
echo "New certificate: "  `openssl x509 -in /etc/$SERVICE/ssl/$DOMAIN.fullchain -noout -subject -dates -issuer`

systemctl reload $SERVICE