#!/bin/sh

. /etc/dehydrated/config

for DOM in $(find $BASEDIR/certs/ -mindepth 1 -maxdepth 1 -type d); do
  CUR_ID=$(readlink $DOM/cert.pem | perl -pe 's/cert-(\d+)\.pem/$1/')
  for ID in $(find $DOM/ -type f -name cert\*.csr -exec basename "{}" \; | perl -pe 's/cert-(\d+)\.csr/$1/'); do
    if [[ "$ID" != "$CUR_ID" ]]; then
      # Is the cert signed ?
      if /usr/bin/openssl x509 -in $DOM/cert-"$ID".pem -noout > /dev/null 2>&1; then
        /usr/bin/dehydrated -r $DOM/cert-"$ID".pem
      else
        # Cert not signed, probably a failed challenge
        rm -f $DOM/cert-"$ID".{pem,csr}
      fi
    fi
  done
done