#!/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

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

  test -r "$crl" || continue
  tmpfile=`mktemp /tmp/ca-crl.XXXXXX`
  final=`mktemp $X509_CERT_DIR/ca-crl.XXXXXX`

#  crl_url=`cat $crl`
#  if [ -n "$crl_url" ]; then
#    mess -n "Retrieving \"$
#    wget -q -t 3 -T 30 "$crl_url" -O $tmpfile && mess ok || mess failed
#  fi
  hashname=`basename "$crl" .crl_url`
  cat "$crl" | while true ; do
    read crl_url
    if [ ! $? = 0 ] ; then break ; fi
    if [ -n "$crl_url" ]; then
      mess -n "For $hashname retrieving \"${crl_url}\":' '"
      wget -q -t 3 -T 30 "$crl_url" -O "$tmpfile"
      if [ $? = 0 ] ; then
        mess ok
        break
      else
        mess failed
        echo -n '' > "$tmpfile"
      fi
    fi
  done
  if [ ! -s "$tmpfile" ] ; then
    rm -f "$tmpfile"
    mess "Warning: CRL for $hashname could not be retrieved"
  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> $final 2> /dev/null
        chmod 644 $final
        # Verify the new crl
        if $openssl crl -in $final -CApath $X509_CERT_DIR 1> /dev/null 2> /dev/null; then
          mv $final $X509_CERT_DIR/$hash.r0
        else
          mess Warning: $X509_CERT_DIR/$hash.r0 could not be verified
        fi
        break
      fi

    done
  fi

  rm -f $tmpfile $final

done
