#!/bin/sh

CERT_SRC="/var/db/acme/certs"

CERT_DST_ROOT="/var/db/certs-for-rsync"
CERT_DST_CERTS="${CERT_DST_ROOT}/certs"

TMP="${CERT_DST_ROOT}/tmp"

# items below here are not usually altered

CONFIG="/usr/local/etc/anvil/cert-shifter.conf"

if [ -f ${CONFIG} ]; then
  . ${CONFIG}
fi

BASENAME="/usr/bin/basename"
CP="/bin/cp"
CMP="/usr/bin/cmp --quiet"
FIND="/usr/bin/find"
GREP="/usr/bin/grep"
LOGGER="/usr/bin/logger -t cert-shifter"
MKDIR="/bin/mkdir"
MV="/bin/mv"
RMDIR="/bin/rmdir"
SYSRC="/usr/sbin/sysrc"

${LOGGER} starting $0

# Find directories, each of which will contain a cert.
# We can't rely on mtimes, because the content may differ
# even with identical mtime.
# Also, the dst and src may get out of sync.
# The complete solution is to scan everything.
# We sort to make it easier when you review the logs.
# 
DIRS=`${FIND} ${CERT_SRC} -type d -d 1 | sort`
for dir in ${DIRS}
do
  cert=`${BASENAME} ${dir}`
  # check the cert config file & ignore anything from staging
  STAGING_USED=`${SYSRC} -qnf ${CERT_SRC}/${cert}/${cert}.conf Le_API | ${GREP} staging`
  if [ ! ${STAGING_USED} ]; then
    REFRESH="0"
    # if the dest directory does not exist, or the dest cert does not exist, or the existing cert differs

    if [ ! -d ${CERT_DST_CERTS}/${cert} -o ! -f ${CERT_DST_CERTS}/${cert}/${cert}.cer ]; then
      # if the destination directory does not exist or the directory does not contain the cert
      # we must copy.
      REFRESH="1"
    else
      # the files, compare them
      `$CMP ${CERT_SRC}/${cert}/${cert}.cer ${CERT_DST_CERTS}/${cert}/${cert}.cer`
      if [ "$?" != "0" ]; then
        REFRESH="1"
      fi
    fi
    
    if [ "$REFRESH" != "0" ]; then
      # copy it over

      ${LOGGER} $cert HAD NEW STUFF IN ${dir}

      # this is not staging
      ${MKDIR} ${TMP}/${cert}
  
      ${CP} -a ${CERT_SRC}/${cert}/${cert}.cer   ${TMP}/${cert}/
      ${CP} -a ${CERT_SRC}/${cert}/ca.cer        ${TMP}/${cert}/
      ${CP} -a ${CERT_SRC}/${cert}/fullchain.cer ${TMP}/${cert}/${cert}.fullchain.cer

      # if the destination directory already exists, overwrite the contents and
      # remove the directory we just created.
      if [ -d "${CERT_DST_CERTS}/${cert}" ]; then
        ${MV} -f ${TMP}/${cert}/* ${CERT_DST_CERTS}/${cert}
        ${RMDIR} ${TMP}/${cert}
      else
        # otherwise, move what we just created into the destination
        # we prefer mv over cp to avoid race conditions.
        ${MV} ${TMP}/${cert} ${CERT_DST_CERTS}/
      fi
    else
      ${LOGGER} $cert
    fi # yeah, the cert has changed
  else
    ${LOGGER} $cert IS BEING IGNORED BECAUSE IT IS STAGING
  fi
done

${LOGGER} stopping $0
