## OpenCA - Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
## (c) Copyright 2002-2004 The OpenCA Project
##
##   File Name: sendcert
##     Version: $Revision: 1.9.2.4 $
##       Brief: submit the ca_certificate
## Description: submit the actual ca-certificate
##  Parameters:                                                                              
use strict;

sub cmdSendcert {

	if ($query->param ('key'))
	{
		my $dataType = $query->param ('dataType') or "VALID_CERTIFICATE";
		my $key      = $query->param ('key');
		my $format   = $query->param ('format');
                $format = $query->param('format_sendcert') if ($query->param('format_sendcert'));

		my $item = $db->getItem (DATATYPE => (uc $dataType), KEY => $key);
		if (not $item)
		{
			generalError (i18nGettext ("Cannot load certificate __SERIAL__.",
			                           "__SERIAL__", $key));
		}

		if ($format =~ /TXT|PEM/i)
		{
			print "Content-type: text/plain\n\n";
		} else {
			my $name = "cert";
                        $name = $item->getParsed()->{DN_HASH}->{CN}[0]
                            if (exists $item->getParsed()->{DN_HASH}->{CN});
			$name =~ s/[^\w.]/_/g;
			print "Content-Disposition: attachment; filename=\"".
                              $name.".".$format.
                              "\"\nContent-type:application/binary\n\n";
		}

		if ($format =~ /DER/i)
		{
			print $item->getDER;
		} elsif ($format =~ /TXT/i) {
			print $item->getTXT;
		} else {
			print $item->getPEM;
		}

	} else {
		my $cacert = getRequired( 'CACertificate' );

		if (not open (FD ,"$cacert")) {
			configError ( gettext ("Can't access CA Certificate!") );
		}

		print "Content-Type: application/x-x509-ca-cert\n\n";

		while (<FD>) {
			print $_;
		}

		close FD;
	}
	return 1;
}

1;
