## OpenCA - Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: removeKey
##       Brief: remove the key from the database
##     Version: $Revision: 1.6.2.2 $
## Description: remove the key from the database finally
##  Parameters: 
 
require "$common_libs/csr-utils.lib";
 
sub cmdRemoveKey {

	my $formFile        = getRequired('RemoveKeyForm');

	## Check FORM : try to identify if the form has already been
	## completed and needs confirmation or if we are in the earlier
	## status ( checking for the correct parameters )

	## Status of FORM, possible values (in this order):
	my $KEY         = $query->param('key');
	my $OPERATION   = $query->param('operation');
	my $DATATYPE    = $query->param('dataType');
	$DATATYPE       = "VALID_CERTIFICATE" if (not $DATATYPE);

	## check for the old passphrase or is it a new change?
	if (not $OPERATION) {
		printFormOne ( FILENAME => $formFile, KEY => $KEY, DATATYPE => $DATATYPE );
		return 1;
	}

	## load cert with key
	my $cert = $db->getItem ( DATATYPE => $DATATYPE, KEY => $KEY);
	if ( not $cert ) {
		generalError (gettext ("Cannot load certificate from database!"));
	}
	my $key = $cert->getParsed()->{KEY};

	## build new cert
	my $new_cert = new OpenCA::X509 ( SHELL => $cryptoShell,
					DATA => $cert->getPEMHeader ().
						$cert->getPEM () );
	if ( not $new_cert ) {
		generalError (gettext ("Cannot create new certificate without key!"));
	}

	## store cert without key
	if (not $db->storeItem ( DATATYPE => $DATATYPE, OBJECT => $new_cert, MODE => "UPDATE" )) {
		generalError (gettext ("Cannot store changed certificate and key in the database!").
                              "<br>".$db->errval(),
		              $db->errno());
	}

	## Send Success Page
	success(gettext ("The key was successfully removed from the database.") );

	return 1;
}

1;

