## OpenCA - CA Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: genSKey
##//       Brief: Generate CA's Secret Key
## Description: Generate The Secrete Key to be used by the CA
##  Parameters: bits, alg, passwd

sub cmdGenSKey {

## This command will generate the new CA secret
## key (private/cakey.pem)

my $baseDoc   = getRequired( 'genskeysheet');

## Get the parameters
my $bits	= $query->param('bits');
my $alg		= $query->param('alg');
my $cakeyFile	= getRequired ( 'CAKey' );

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

if( -e "$cakeyFile" ) {
	$tools->moveFiles( SRC=>"$cakeyFile", DEST=>"${cakeyFile}.${$}_old" );
	$msg = i18nGettext ("Old key file is (__FILE__).", "__FILE__", "${cakeyFile}.${$}_old");
}

$errno = 0;
if ($ENV{'engine'})
{
    my $command = getRequired ('HSM_GENKEY_CMD');
    $command = $query->subVar ($command, '@__BITS__@', $bits);
    $command = $query->subVar ($command, '@__OUTFILE__@', $cakeyFile);
    my $ret = `$command`;
    if ($? != 0)
    {
        $errno  = $?;
        $errval = $ret;
	$msg .= "<br>\n".
                "<FONT COLOR=#FF0000>".
                i18nGettext ("HSM utility failed: __COMMAND__", "__COMMAND__", $command).
	        "<br>\n".
                i18nGettext ("Errorcode: __ERRNO__", "__ERRNO__", $?).
	        "<br>\n".
                i18nGettext ("Errormessage: __ERRVAL__", "__ERRVAL__", $ret).
                "</FONT>";
    }
} else {
    my $pwd = $query->param('passwd');
    if( not $cryptoShell->genKey( BITS      => $bits,
                                  OUTFILE   => $cakeyFile,
                                  ALGORITHM => $alg,
                                  PASSWD    => $pwd ) ) {
        $errno  = $OpenCA::OpenSSL::errno;
        $errval = $OpenCA::OpenSSL::errval;
	$msg .= i18nGettext ("OpenCA::OpenSSL failed: __ERRNO__", "__ERRNO__", $OpenCA::OpenSSL::errno).
	        "<br>\n".
            i18nGettext ("Errormessage: __ERRVAL__", "__ERRVAL__", $OpenCA::OpenSSL::errval);
    }
}

if ($errno)
{
    $key = "&nbsp;";
} else {
    ## Try loading the Key File
    $key = $query->getFile( "$cakeyFile" );
}

## 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', $key );
$page = $query->subVar( $page, '$msg', $msg );

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

}

1;
