#!/usr/bin/env perl

my $cert = "";
my $seenbegin = 0;
my $count = 0;

if (@ARGV != 1) {
    printf "Usage: $0 <output-prefix>"
}

while (<STDIN>) {
    if ($_ =~ /^-----BEGIN CERTIFICATE-----$/) {
        $seenbegin = 1;
    }

    if ($seenbegin) {
        $cert .= $_;
    }

    if ($_ =~ /^-----END CERTIFICATE-----$/) {
        my $file = $ARGV[0] . "-" . sprintf("%03d", $count) . ".pem";

        open OUT, ">$file";
        $certinfo = `echo "$cert" | openssl x509 -subject -fingerprint -dates -noout`;
        print OUT $certinfo;
        print OUT $cert;
        close OUT;

        $cert = "";

        print "$file\n";

        $seenbegin = 0;
        $count++;
    }
}
