#!/usr/bin/env bash

# Then endpoint for the s3 compatible storage in most cases a minio install
ENDPOINT_URL="https://minio.example.com"

# Some services prefere a pfx cert store file the follwing password ist for that store.
PFX_PASSWORD=securepw

####################################################
set -e

RENEWED_DOMAINS=`ls /etc/letsencrypt/live/`
echo $RENEWED_DOMAINS
for domain in $RENEWED_DOMAINS; do
echo $domain
  DOMAINNAME=`openssl x509 -noout -text -in /etc/letsencrypt/live/$domain/cert.pem | grep DNS: | sed 's/^.*,//' | sed 's/^.*DNS://'`
  cat "/etc/letsencrypt/live/$domain/fullchain.pem" "/etc/letsencrypt/live/$domain/privkey.pem" > /tmp/$DOMAINNAME.pem
  openssl pkcs12 -export -out /tmp/$DOMAINNAME.pfx -inkey "/etc/letsencrypt/live/$domain/privkey.pem" -in "/etc/letsencrypt/live/$domain/cert.pem" -certfile "/etc/letsencrypt/live/$domain/chain.pem" -certfile "/etc/letsencrypt/live/$domain/fullchain.pem" -password pass:$PFX_PASSWORD
   # Just an example, you can use any non-sensitive storage medium you want
  aws --endpoint-url $ENDPOINT_URL s3 cp --follow-symlinks "/etc/letsencrypt/live/$domain/fullchain.pem" "s3://certs/$DOMAINNAME.fullchain"
  aws --endpoint-url $ENDPOINT_URL s3 cp --follow-symlinks "/etc/letsencrypt/live/$domain/chain.pem" "s3://certs/$DOMAINNAME.chain"
  aws --endpoint-url $ENDPOINT_URL s3 cp --follow-symlinks "/etc/letsencrypt/live/$domain/cert.pem" "s3://certs/$DOMAINNAME.crt"
  aws --endpoint-url $ENDPOINT_URL s3 cp --follow-symlinks "/etc/letsencrypt/live/$domain/privkey.pem" "s3://certs/$DOMAINNAME.key"
  aws --endpoint-url $ENDPOINT_URL s3 cp --follow-symlinks "/tmp/$DOMAINNAME.pem" "s3://certs/$DOMAINNAME.pem"
  aws --endpoint-url $ENDPOINT_URL s3 cp --follow-symlinks "/tmp/$DOMAINNAME.pfx" "s3://certs/$DOMAINNAME.pfx"
  rm -f /tmp/$DOMAINNAME.pem
  rm -f /tmp/$DOMAINNAME.pfx
done