#!/bin/sh

# update_crls: Retrieve various crl's and install them.
#
# Anders Waananen 20020717
#
# Description:
#   The script tries to download known crl's and save them
#   using the hash form for the filename. If 'quiet' is given
#   as argument the script will be silent. This is useful if
#   run from cron.
#
#   The URLs for the CRLs are taken from the files:
#      /etc/grid-security/certificates/*.crl_url
# 

# Change this to the local setting

QUIET=YES
[ "$1" = "verbose" ] && QUIET=NO

function mess () {
  [ "$QUIET" = "NO" ] && eval echo -e $*
}

# Some intelligent openssl discovery should be here.
openssl=openssl
X509_CERT_DIR=${X509_CERT_DIR:-/etc/grid-security/certificates}

for crl in $X509_CERT_DIR/*.crl_url; do

  tmpfile=`mktemp /tmp/ca-crl.XXXXXX`

  crl_url=`cat $crl`
  if [ -n "$crl_url" ]; then
    mess -n "Retrieving \"${crl_url}\":' '"
    wget -q -t 3 -T 30 "$crl_url" -O $tmpfile && mess ok || mess failed
  fi

  if [ -r "$tmpfile" ]; then
    for format in PEM DER ; do
      hash=`$openssl crl -inform $format -in $tmpfile -noout -hash 2>/dev/null`

      if [ -n "$hash" ]; then
        $openssl crl -inform $format -in $tmpfile -outform PEM 1> $X509_CERT_DIR/$hash.r0 2>/dev/null
#        cp -f $tmpfile $X509_CERT_DIR/$hash.r0
        chmod 644 $X509_CERT_DIR/$hash.r0
        if [ ! -r $X509_CERT_DIR/$hash.0 ]; then
          mess Warning: $X509_CERT_DIR/$hash.0 is not installed
        fi
        break
      fi

    done
  fi

  rm -f $tmpfile

done
