## OpenCA - Public Web-Gateway Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: getcert
##       Brief: send certs
## Description: send certificates over http (used for certificateenrollment) 
##  Parameters: 
 
sub cmdGetcert {

##// Let's get parameters
my $type      = $query->param('type');
my $key       = ( $query->param('key') || $query->param('serial') );
my $dataType  = ( $query->param('dataType') || "VALID_CERTIFICATE" );

my $cert = undef;

## Certificates directory
my $tmpdir   = getRequired( 'tempdir' );

## which type is requested?
if ($type =~ /CSR/i) {
    my @list = $db->searchItems (DATATYPE => $dataType, CSR_SERIAL => $key);
    $cert = $list[0] if (@list);
} elsif ($type =~ /BATCH/i) {
    my $batch_dir = getRequired ("BP_DIR");

    ## build the directory path for the ID
    my $id_dir = $batch_dir;
    my $h_id   = $key;
    while ($h_id !~ /^$/) {
        $id_dir .= "/".substr $h_id, 0, 1;
        $h_id =~ s/^.//;
    }

    ## check that the directory not exist
    if (-d $id_dir) {
        ## checking that this directory is only part of a tree
        if (not -f $id_dir."/ID") {
	    print "Content-type: text/html\n\n";
	    generalError (
            i18nGettext ( "Directory __DIR__ exists but it is not the directory of a user. Cannot update a nonexistent user. Ignoring dataset of ID __ID__.",
                          "__DIR__", $id_dir,
                          "__ID__", $key));
        }
    } else {
	print "Content-type: text/html\n\n";
        generalError (
            i18nGettext ( "Directory __DIR__ does not exist. Cannot update a nonexistent user. Ignoring dataset of ID __ID__",
                          "__DIR__", $id_dir,
                          "__ID__", $key));
    }

    ## load latest request serial
    my $old_serial = $tools->getFile ($id_dir."/.csr");
    $old_serial =~ s/\n.*$//; ## use only the last csr
    if (not $old_serial) {
	print "Content-type: text/html\n\n";
        generalError (i18nGettext ("There is no old request. Ignoring dataset of ID __ID__.", "__ID__", $key));
    }

    ## load cert
    my @list = $db->searchItems (DATATYPE => $dataType, CSR_SERIAL => $old_serial);
    $cert = $list[0] if (@list);
} else {
    $cert = $db->getItem(DATATYPE => $dataType, KEY => $key);
}

## Error if the certificate is not present in DBMS
if ( not $cert ) {
	print "Content-type: text/html\n\n";
	generalError (gettext ("Cannot load certificate from the database!"));
}

my $mycert = $cert->getPEM();
if (not $mycert){
	print "Content-type: text/html\n\n";
	generalError (gettext ("Cannot load necessary form!"));
}

## Get User Agent
my $agent = $query->user_agent();

if ( $agent =~ /MSIE/ ) {
	## MS Internet Explorer

	my $form = $tools->getFile (getRequired ('IE_EnrollForm'));
	if (not $form) {
		print "Content-type: text/html\n\n";
		generalError (gettext ("Cannot load necessary form!"));
	}

	my $cacert = getRequired( "CACertificate" );

	my $fileName= $tmpdir."/${$}_getcert.pem";
	if (not $tools->saveFile ( FILENAME => $fileName, DATA => $mycert )) {
		print "Content-type: text/html\n\n";
		generalError (gettext ("Cannot write PEM-formatted certificate into temporary file!"));
	}
	my $certpk7 = $cryptoShell->crl2pkcs7 ( 
				OUTFORM   => 'PEM',
				# if the user load the CA-certificate before he start
				# the request then we must not send the CA-certificate
				# CERTSLIST => ["$cacert","$fileName"]
				CERTSLIST => [$fileName]);
	unlink ( $fileName );
	if (not $certpk7) {
		print "Content-type: text/html\n\n";
		generalError (gettext ("Cannot convert certifcate to PKCS#7!"));
	}
	$certpk7 =~ s/\n//g;
	$certpk7 =~ s/-----BEGIN PKCS7-----//g;
	$certpk7 =~ s/-----END PKCS7-----//g;

	$form = $query->subVar($form,'$certpk7',$certpk7);
	$form = $query->subVar($form,'$browser',"IE");

	print "Content-type: text/html\n\n";
	print $form;
	## print "Content-type: application/x-x509-email-cert\n\n";
	## print $cert->getDER();
} else {
	## Mozilla
	print "Content-type: application/x-x509-user-cert\n\n";
	print $mycert;
}

}

1;
