##
##  x509-ca.pl -- Regenerate "x509-ca.crt" from Mozilla "certdata.txt"
##  Copyright (c) 2002-2014 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 $certdata = "https://hg.mozilla.org/releases/mozilla-release/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt";

my $date = `date`;
$date =~ s/\n$//s;
print <<EOH;
##
##  x509-ca.crt -- Certificate Authority (CA) X.509 Root Certificates
##
##  This Source Code Form is subject to the terms of the Mozilla Public
##  License, v. 2.0. If a copy of the MPL was not distributed with this
##  file, You can obtain one at http://mozilla.org/MPL/2.0/.
##
##  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/x509-ca.crt", X509_FILETYPE_PEM);
##  X509_verify_cert([...]);
##
##  Source: $certdata
##  Last Modified: $date
##

EOH
open(IN, "curl -s -k $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 '';
        }
    }
}
close(IN);

