:
eval 'exec perl -S $0 ${1+"$@"}'
    if $running_under_some_shell;

##
##  cert_bundle -- Bundle CA Certificates into one file
##  Copyright (c) 1998 Ralf S. Engelschall, All Rights Reserved. 
##

($certdb, $indexfile, $bundlefile) = @ARGV;

%CERT = ();
open(IDX, "<$indexfile") || die;
while (<IDX>) {
    if (m|^(\S+):\s+(.+)\s*$|) {
        $CERT{$2} = $1;
    }
}
close(IDX);

$date = `date`;
$date =~ s|\n$||;
open(BDL, ">$bundlefile") || die;
print BDL "##\n";
print BDL "##  $bundlefile -- Bundle of CA Certificates\n";
print BDL "##  Last Modified: $date\n";
print BDL "##\n";
print BDL "##  This is a bundle of X.509 certificates of public\n";
print BDL "##  Certificate Authorities (CA). These were automatically\n";
print BDL "##  extracted from Netscape Communicator's certificate database\n";
print BDL "##  (the file `$certdb').\n";
print BDL "##\n";
foreach $cert (sort(keys(%CERT))) {
    $file = $CERT{$cert};
	print STDERR "Bundling: $cert ($file)\n";
    $pem = `openssl x509 -in $file -inform DER -outform PEM`;
    $pem =~ s|\n$||;
    $purpose = `openssl x509 -in $file -inform DER -noout -purpose`;
    #
    $_ = $purpose;
    if ( /server CA : Yes\n/ || /client CA : Yes\n/ || (/Any Purpose CA : Yes\n/ && (/client : Yes\n/ || /server : Yes\n/ ))) {
       print BDL "\n";
       print BDL "$pem\n";
    }
}
close(BDL);

