#!/bin/bash
# Update the Certificate Revokation List
#
# © 2012, Multapplied Networks, Inc.
set -e
. /usr/share/bondingadmin/default/ca-vars

cd $BONDINGADMIN_DIR

# If the disk is out of space, OpenSSL will clear the crl and crlnumber files
# We will copy the crlnumber temporarily, and if it works we will save the new
# crl file and check its size prior to overwriting the old one.
TMP_CRL_FILE="$CRL_FILE.tmp"
TMP_CRLNUMBER_FILE="$CRLNUMBER_FILE.tmp"

cp $CRLNUMBER_FILE $TMP_CRLNUMBER_FILE

if [ $? == "0" ]; then
    $OPENSSL ca -config $CONFIG -gencrl -out $TMP_CRL_FILE 2> /dev/null # OpenSSL prints to STDERR by default, fail.
    sync  # du reports 0 bytes until the cached writes are written
    if [[ -f $TMP_CRL_FILE && "$(du $TMP_CRL_FILE | awk '{print $1}')" -gt "0" ]]; then
        # If we wrote a non-empty crl, overwrite the old crl
        cp $TMP_CRL_FILE $CRL_FILE
    else
        # OpenSSL cleared the crlnumber file, so restore our backup
        mv $TMP_CRLNUMBER_FILE $CRLNUMBER_FILE
    fi

    USER=`/usr/bin/whoami`
    if [ "$USER" == "root" ]; then
        chown -R $HTTPD_USER:$HTTPD_GROUP $CA_DIR
    fi

    # Clean up our tmp files
    rm -f $TMP_CRLNUMBER_FILE $TMP_CRL_FILE
fi
