#! /usr/bin/perl -w
#
use strict;
use Getopt::Long qw(:config no_ignore_case bundling);

my $sccsid = '@(#)$Id: clean-crl.cin 2649 2013-07-02 18:55:45Z davidg $';

my $targetdir;
my $show_help;
my $show_version;
my $verbose;
my $dryrun;

sub help() {
  (my $name = $0) =~ s/.*\///;
  print <<EOHELP;
The $name utility will eradicate [0-9a-f]{8}.r\\d+ files from
the directory given to the "-l" option if no matching [0-9a-f]{8}.\\d+
file can be found in the same, which in most cases will wipe stale 
historic CRLs from an X509_CERT_DIR like directory.
Use at your own risk. It may be wiping files that you would have
liked to keep, or it may kill your pet.

Options:
  -l | --cadir <path>
    directory to cleanse of old CRL-ish files
  -v[v...] | --verbose 
    become more verbose and talkative
  -n | --dryrun
    do not actually unlink any files
  -V | --version
    show a version number
  -h | --help
    this help text

Examples:
  $name -l /etc/grid-security/certificates

Diagnostics:
  ". not found": consult an expert.

EOHELP
  return 1;
}

sub showversion() {
  (my $name = $0) =~ s/.*\///;
  print "$name version 3.0.19\n";
  return 1;
}

&GetOptions(
  "l|cadir=s" => \$targetdir,
  "n|dryrun" => \$dryrun,
  "h|help" => \$show_help,
  "v|verbose+" => \$verbose,
  "V|version" => \$show_version
  ) or &help and exit(1);

$show_help and &help() and exit (0);
$show_version and &showversion() and exit (0);
$verbose = 0 unless defined $verbose;
$dryrun = 0 unless defined $dryrun;

die "Error: target directory undefined, please supply -l argument!\n" 
  unless $targetdir;
die "Error: target directory $targetdir does not exist\n"
  unless -e $targetdir;
die "Error: target directory $targetdir is not a directory\n"
  unless -d $targetdir;

# read the directory and find all CA like .\d and CRL like files, 
# recoding the hashes of the info files in an array, and then in a
# second pass weeding out those CRL ".r*" files that do not have
# a corresponding info or crl_url file
# the remainer is a candidate for deletion
my $dh;
my @crlfiles;
my %infohashes;
opendir($dh,$targetdir) or die "Cannot open $targetdir: $!\n";
while ( my $fn = readdir $dh ) {
  $fn =~ /^([0-9a-f]{8})\.(\d+)$/ and do {
    $infohashes{$1}=1;
    ($verbose > 2) and print "Hash $1 belongs to an active CA\n";
  };
  $fn =~ /^([0-9a-f]{8})\.r(\d+)$/ and do {
    push @crlfiles,$fn;
    ($verbose > 2) and print "File $fn is classified as a CRL file\n";
  };
}

my @candidates = grep {
    /^([0-9a-f]{8})\.r([0-9]+)$/;
    ! exists $infohashes{$1};
  } @crlfiles;

$verbose > 0 and do {
  if ( $#candidates >= 0 ) {
    print "The following CRL like files are about to be deleted".
      ($dryrun?" ... NOT!":".")."\n";
    foreach my $fn ( @candidates ) { print "  $fn\n"; }
  } else {
    print "No orphaned CRL like files found in $targetdir\n";
  }
};

if ( ! $dryrun ) {
  foreach my $fn ( @candidates ) { 
    unlink("$targetdir/$fn") or warn "Cannot remove $targetdir/$fn: $!\n";
  }
}

1;
