## OpenCA - Public Web-Gateway Command
## (c) 1998-2001 by OpenCA Group
##
##   File Name: approveCRRnotSigned
##       Brief: store the revreq to the DB
## Description: store the revreq to the DB for RA Operator approval
##  Parameters: head, text, signature

sub cmdApproveCRRnotSigned {

## Reserved variables
my ( $text, $cert, @search, $certTable );

## Get required configuration parametes
my $basedoc     = getRequired( "RevReqSuccessSheet" );

## To aprove a Request, we need it signed by the RA operator
my $beginHeader = "-----BEGIN HEADER-----";
my $endHeader = "-----END HEADER-----";

## Get the parameters
my $head        = $query->param('head');
my $body        = $query->param('text');

## Load base page
my $page = $query->getFile ( $basedoc );
if ( not $page ) {
	configError ( i18nGettext ("Cannot load file __PAGE__!", "__PAGE__", $page));
}

my $req_txt = $head . $body;

## Try to build the REQ object
my $req = new OpenCA::REQ ( SHELL=>$cryptoShell, DATA=>$req_txt );
if( not $req ) {
	configError( gettext ("Error while creating the request."));
}

## check for the old request and attach the signature of the user
my $h = $db->getItem (DATATYPE => "CRR", KEY => $req->getSerial());
$req_txt .= $h->getParsed()->{SIGNATURE} if ($h);

$req = new OpenCA::REQ ( SHELL=>$cryptoShell, DATA=>$req_txt );
if( not $req ) {
	configError( gettext ("Error while creating the request."));
}

## download the certificate
my $cert = $db->getItem ( DATATYPE => "CERTIFICATE", KEY => $req->getParsed()->{REVOKE_CERTIFICATE_SERIAL} );
if (not $cert) {
	##// it's not good to show the user the detailed problem
	my $basedoc = getRequired ('db_error');
	print $tools->getFile ( $basedoc );
	return undef;
}

if ( not $db->updateStatus ( OBJECT=>$req, DATATYPE=>"PENDING_CRR", NEWTYPE => "APPROVED_CRR" )) {
	if ( not $db->storeItem( OBJECT=>$req, DATATYPE=>"APPROVED_CRR", MODE => "INSERT" )) {
		print STDERR "SECURITY ALERT BY PKI: database failed during storing a correct CRR which follows\n".
			$req_txt."\n";
		configError( gettext ("Error while storing the request."));
	}
}

if (not (
     $db->updateStatus ( OBJECT => $cert, DATATYPE=>"VALID_CERTIFICATE", NEWTYPE => "SUSPENDED_CERTIFICATE") or
     $db->updateStatus ( OBJECT => $cert, DATATYPE=>"EXPIRED_CERTIFICATE", NEWTYPE => "SUSPENDED_CERTIFICATE"))) {
	if ( not $db->getItem (DATATYPE=>"SUSPENDED_CERTIFICATE", KEY=>$cert->getSerial()) and
	     not $db->getItem (DATATYPE=>"REVOKED_CERTIFICATE",   KEY=>$cert->getSerial()) ) {
		print STDERR "SECURITY ALERT BY PKI: database failed during storing a correct CRR which follows\n".
			$req_txt."\n";
		configError( gettext ("Failed to change the certificate's state."));
	}
}

print "$page";

}

1;
