##
##  x509-ca.pl -- Regenerate "x509-ca.crt" from Mozilla "certdata.txt"
##  Copyright (c) 2002-2009 Ralf S. Engelschall <rse@engelschall.com> 
##
##  This program is free software; you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation; either version 2 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
##  General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program; if not, write to the Free Software
##  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
##  USA, or contact Ralf S. Engelschall <rse@engelschall.com>.
##

#   configuration
my $cvsroot  = ':pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot';
my $certdata = 'mozilla/security/nss/lib/ckfw/builtins/certdata.txt';

my $date = `date`;
$date =~ s/\n$//s;
print <<EOH;
##
##  public-ca.crt -- Certificate Authority (CA) A X.509 Root Certificates
##
##  This is a bundle of X.509 root certificates of public Certificate
##  Authorities (CA). These were automatically extracted from Mozilla's
##  root CA list (the file "certdata.txt"). It contains the certificates
##  in both plain text and PEM format and therefore can be directly used
##  with any OpenSSL based applications.
##
##  To use this file, specify it as the "CAfile" argument to the "openssl"
##  commands like "smime" or "verify", or use a C code fragment like this:
##
##  X509_STORE *cert_ctx;
##  X509_LOOKUP *lookup;
##  static int cb(int ok, X509_STORE_CTX *ctx);
##  cert_ctx = X509_STORE_new();
##  X509_STORE_set_verify_cb_func(cert_ctx, cb);
##  lookup = X509_store_add_lookup(cert_ctx, X509_LOOKUP_file());
##  X509_LOOKUP_load_file(lookup, "/path/to/public-ca.crt", X509_FILETYPE_PEM);
##  X509_verify_cert([...]);
##
##  Last Modified: $date
EOH
open(IN, "cvs -d $cvsroot co -p $certdata|")
    || die "could not check out certdata.txt";
my $incert = 0;
while (<IN>) {
    if (/^CKA_VALUE MULTILINE_OCTAL/) {
        $incert = 1;
        open(OUT, "|openssl x509 -text -inform DER -fingerprint")
            || die "could not pipe to openssl x509";
    } elsif (/^END/ && $incert) {
        close(OUT);
        $incert = 0;
        print "\n\n";
    } elsif ($incert) {
        my @bs = split(/\\/);
        foreach my $b (@bs) {
            chomp $b;
            printf(OUT "%c", oct($b)) unless $b eq '';
        }
    } elsif (/^CVS_ID.*Revision: ([^ ]*).*/) {
        print "##  Source: \"certdata.txt\" CVS revision $1\n##\n\n";
    }
}
close(IN);

