#!/bin/sh

# pkix_setup - synchronize the old and new X.509 device certificate
#              directories following a software upgrade or downgrade

source /ciena/scripts/utils.sh

# X.509 certificate locations (cf. linux.h)

CERT_DIR=/flash0/cert                       # base directory for certificates
CERT_DEV_DIR=${CERT_DIR}/dev                # Device certificates
DOT1X_CERT_DIR=${CERT_DIR}/supp             # 802.1x supplicant key/certificates by port name
[ -d ${CERT_DIR} ] || die 1 "$(basename $0): Directory ${CERT_DIR} does not exist"
[ -d ${CERT_DEV_DIR} ] || die 1 "$(basename $0): Directory ${CERT_DEV_DIR} does not exist"

# If the old 802.1x supplicant certificate directory is already a symbolic
# link, we don't need to do anything else to it.
if [ ! -L ${DOT1X_CERT_DIR} ]; then
    if [ -d ${DOT1X_CERT_DIR} ]; then
        # Assume that the file names in this directory may contain spaces, so
        # "for file in *" won't work and strings containing ${file} have to be
        # quoted.
        /bin/ls ${DOT1X_CERT_DIR} | while read file; do
            # If the certificate file in the new directory does not exist or
            # is older than the file in the old directory, move the file from
            # the old directory to the new directory and create a symbolic link
            # from the old file to the new file.
            if [ ! -f "${CERT_DEV_DIR}/${file}" ] ||
                [ "${CERT_DEV_DIR}/${file}" -ot "${DOT1X_CERT_DIR}/${file}" ]; then
                /bin/mv -f "${DOT1X_CERT_DIR}/${file}" "${CERT_DEV_DIR}/${file}"
                /bin/ln -sf "${CERT_DEV_DIR}/${file}" "${DOT1X_CERT_DIR}/${file}"
            fi
        done
        # A directory cannot be replaced by a symbolic link, so we remove the
        # directory and its remaining contents first.
        rm -rf ${DOT1X_CERT_DIR}
    fi
    /bin/ln -sf ${CERT_DEV_DIR} ${DOT1X_CERT_DIR}
fi
