## OpenCA - CA Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: bpExportPIN
##     Version: $Revision: 1.12 $
##       Brief: export PINs for new users
## Description: 
##  Parameters:

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

sub cmdBpExportPIN {

	print startLogPage (gettext ("Export PIN Batch Processor"));

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

	my $tmpdir = createDirectory ();

	if (not open FD, ">$tmpdir/$batch_file") {
		print addLogSection (gettext ("Try to open file for export PINs ...failed."));
		print closeLogSection ();
		print closeLogPage ();
		return undef;
	}

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

	bpScanDir ($batch_dir, "bpExportPIN");

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

	close FD;

	eximIOExport (DIR => $tmpdir);

	removeDirectory ($tmpdir);

	print closePage();

}

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

	## check for ID
	if ( (-f $dir."/ID") and
	     (-f $dir."/private/purePIN") and
	     (-f $dir."/public/hashedPIN") ) {

		## export PIN
		my $ID  = $tools->getFile ($dir."/ID");
		if (not $ID) {
			print addPreLogLine (
				    "<FONT COLOR=#FF0000>".
				    i18nGettext (
                      "Cannot load ID from file! Ignoring directory __DIR__.",
                      "__DIR__", $dir).
				    "</FONT>");
		}

		my $PIN = $cryptoShell->getSMIME (
		                                  DECRYPT    => 1,
		                                  CERT       => getRequired ("BP_CERTIFICATE"),
		                                  KEY        => getRequired ("BP_KEY"),
		                                  USE_ENGINE => 1,
		                                  PASSWD     => $query->param ('passwd'),
		                                  INFILE     => $dir."/private/purePIN",
		                                  );
		if (not $PIN) {
			print addPreLogLine (
			                     "<FONT COLOR=#FF0000>".
			                     i18nGettext (
			                                  "Cannot decrypt file __FILE__! Ignoring ID __ID__",
			                                  "__FILE__", $dir."/private/purePIN",
			                                  "__ID__", $ID).
			                     "</FONT>");
		}
		( $PIN ) = ( $PIN =~ /-----BEGIN PIN-----[\n\r]*([^\n\r]*)[\n\r]*-----END PIN-----/i);
		if (not $PIN) {
			print addPreLogLine (
				    "<FONT COLOR=#FF0000>".
				    i18nGettext (
                      "Cannot extract PIN from decrypted file! Ignoring ID __ID__",
                      "__ID__", $ID).
				    "</FONT>");
		}
		if ($PIN and $ID) {
			print FD "ID ".$ID."\n";
			print FD "PIN ".$PIN."\n\n";
			print addPreLogLine (i18nGettext ("ID: __ID__ - PIN exported", "__ID__", $ID));
		}
	}
}

1;
