## OpenCA - CA Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: genCAReq
##       Brief: Generate CA Request
##// Description: Generate CA's certificate Request
##  Parameters: email, cn, ou, o, c, pwd

sub cmdGenCAReq {

## This command will generate the $openca/ca_req.pem
## that should be exported to the root ca for approval

my $baseDoc   	= getRequired( 'gencareqsheet');

## Get the parameters
my $email	= $query->param('email');
my $cn		= $query->param('cn');
my $ou		= $query->param('ou');
my $o		= $query->param('o');
my $c		= $query->param('c');
my $pwd		= $query->param('passwd');
my $dn		= $query->param('dn');

## this is the important part !!!
if ($dn =~ /^ *$/) {
  $dn = "";
}

my $careqFile	= getRequired ( 'ReqDir' ) . '/careq.pem';
my $cakeyFile	= getRequired ( 'CAKey' );

## Other reserved variables
my ( $page, $ret, $key );

## Check the private key
if( not ( -e "$cakeyFile" ) ) {
 	configError(gettext ("Private key is missing, please generate a new one!"));
}

## Remove the old careq file, it is not important to keep a
## copy of it. As it is very simple to generate a new one.
unlink( "$careqFile") if( -e "$careqFile" );

## Send parameters: it is important that you send them
## in the same order as they are asked for. This means
## email->cn->ou->o->c
if (not $cryptoShell->genReq( KEYFILE => "$cakeyFile",
			USE_ENGINE    => 1,
			OUTFILE       => "$careqFile",
			DN            => [ "$email", "$cn", "$ou", "$o", "$c" ],
			SUBJECT       => "$dn",
			PASSWD        => $pwd )) {
	generalError (gettext ("OpenCA::OpenSSL failed.")."<br>\n".
			$OpenCA::OpenSSL::errval, $OpenCA::OpenSSL::errno);
}

## Try loading the Req File
my $req = new OpenCA::REQ ( SHELL  => $cryptoShell, INFILE => "$careqFile" );

if( not $req ) {
	$msg = "<BR>".gettext ("Cannot initialize an new object of OpenCA::REQ.")."<BR><BR>\n";
	$msg .= "($email, $cn, $ou, $o, $c)<br>\n";
	$msg .= "(Subject: $dn)<br><br>\n";
	$msg .= $OpenCA::REQ::errval;
	generalError ( $msg, $OpenCA::REQ::errno );
}

## If we cannot load the base Document, then error
configError(i18nGettext ("Cannot load file __FILE__!", "__FILE__", $baseDoc))
		 unless ( $page = $query->getFile("$baseDoc"));

## Substitute the variables
$page = $query->subVar( $page, '$key', $req->getTXT() );
$page = $query->subVar( $page, '$msg', $msg );

## Send out the page
print "$page";

}

1;


