## OpenCA - CA Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: exportPKCS12
##     Version: $Revision: 1.5 $
##       Brief: export PKCS#12-files
## Description: export PKCS#12-files for users
##  Parameters:

require "$common_libs/export-import.lib";

sub cmdBpExportPKCS12 {

	print startLogPage (gettext ("Export PKCS#12 Batch Processor"));

	## datadirectory for the batchprocessor
	my $batch_dir  = getRequired ("BP_DIR");

	print addLogSection (gettext ("Running batch processor ..."));

	bpScanDir ($batch_dir, "bpExportPKCS12");

	print addPreLogLine ("");
	print addLogLine (gettext ("Batch processor finished"));
	print closeLogSection ();

	eximIOExport (DIR => getRequired ("BP_EXPORT_PKCS12_DIR"));

	print closePage();

}

sub bpExportPKCS12 {
	my $dir = $_[0];

	return if (not -f $dir."/ID");
	return if (not -f $dir."/private/purePIN");
	return if (not -f $dir."/private/privateKey");
	return if (not -f $dir."/public/csrList");

	## get CSRs
	my $reqfile = $tools->getFile ($dir."/public/csrList");
	my @csrList    = split /\n/, $reqfile;

	## get last csr with cert
	@csrList = reverse @csrList;
	my $csr;
	my $cert = undef;
	while (scalar @csrList) {
		$csr = pop @csrList;
		my @certList = $db->searchItems (DATATYPE => "VALID_CERTIFICATE", CSR_SERIAL => $csr);
		$cert = @certList [0] if (@certList);
		@csrList = () if ($cert);
	}

	## check presence of cert
	return if (not $cert);

	## build pkcs#12
	my $cacert = getRequired ('CACertificate');
	my $passwd = $cryptoShell->getSMIME (
	                                  DECRYPT    => 1,
	                                  CERT       => getRequired ("BP_CERTIFICATE"),
	                                  KEY        => getRequired ("BP_KEY"),
                                          USE_ENGINE => 1,
	                                  PASSWD     => $query->param ('passwd'),
	                                  INFILE     => $dir."/private/purePIN",
	                                  );
	( $passwd ) = ( $passwd =~ /-----BEGIN PIN-----[\n\r]*([^\n\r]*)[\n\r]*-----END PIN-----/i);
	if (not $passwd) {
		print addPreLogLine (
		          "<FONT COLOR=#FF0000>".
		          i18nGettext (
			      "Cannot load the PIN because the decryption of the PIN failed - ID __ID__ ignored.",
		              "__ID__", $tools->getFile ($dir."/ID")).
		          "</FONT>");
		return;
	}
	my $data = $cert->getPEM();
	my $keyfile = $dir."/private/privateKey";
	my $p12_data = $cryptoShell->dataConvert (
	                                          DATA      => $data,
	                                          DATATYPE  => "CERTIFICATE",
	                                          KEYFILE   => $keyfile,
	                                          INFORM    => "PEM",
	                                          OUTFORM   => "PKCS12",
	                                          PASSWD    => $passwd,
	                                          P12PASSWD => $passwd,
	                                          CACERT    => $cacert);

	if (not $p12_data) {
		print addPreLogLine (
		          "<FONT COLOR=#FF0000>".
		          i18nGettext (
                      "Cannot export PKCS#12-file because the creation of the PKCS#12-data failed (errorcode __ERRNO__) - ID __ID__ ignored",
		              "__ID__", $tools->getFile ($dir."/ID"),
		              "__ERRNO__", $OpenCA::OpenSSL::errno
		                      ).
		          "</FONT>");
		return;
	}

	## export pkcs#12
	my $export_dir = getRequired ("BP_EXPORT_PKCS12_DIR");
	my $file = $export_dir."/".$tools->getFile ($dir."/ID").".p12";
	if (not $tools->saveFile (FILENAME => $file, DATA => $p12_data)) {
		print addPreLogLine (
		          "<FONT COLOR=#FF0000>".
		          i18nGettext (
                      "Cannot export PKCS#12-file because the creation of the PKCS#12-file __FILE__ failed (errorcode __ERRNO__) - ID __ID__ ignored",
		              "__ID__", $tools->getFile ($dir."/ID"),
		              "__FILE__", $file
		                      ).
		          "</FONT>");
		return;
	} else {
		print addPreLogLine (i18nGettext ("Exported PKCS#12-file for ID __ID__.", "__ID__", $tools->getFile ($dir."/ID")));
		return 1;
	}
}

1;
