#! /usr/bin/perl -w

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use LWP::Simple;
use URI::URL;

# Variables
my $hostname = "localhost";
my ($CAName, $CRLURL, $exportURL, $CRLLifeDays);
my $CRL = 0;
my $CRLRequested = 0;

# Handle command line parameters
# CANAME CRLURL EXPORTURL CRLLIFE

# Check numbers of parameters
if (scalar(@ARGV) != 4) {
	print "Error: call as CAGEN CAName CRLURL exportURL CRLLifeDays\n";
	die;
}

$CAName = $ARGV[0];
$CRLURL = $ARGV[1];
$exportURL = $ARGV[2];
$ARGV[3] =~ s/[^0-9]//g;
$CRLLifeDays = $ARGV[3];

if (not -e "/var/www".$CRLURL ) {
	print "Error: CRLURL does not exist.\n";
	die;
}

if (not -e "/var/www".$CRLURL ) {
	print "Error: exportURL does not exist.\n";
	die;
}

if ( (length ($CRLLifeDays) == 0) or ($CRLLifeDays < 4) or ($CRLLifeDays > 30) ) {
	print "Error: CRL life must be between 4 and 30 days.\n";
	die;
}

# print $CAName.":".$CRLURL.".".$exportURL.":".$CRLLifeDays;

while ( ! $CRL ) {
	# First get the CA password
	print "Please enter the CA password for the ".$CAName." (Q to skip):\n";
	$passwd = <STDIN>;
	chomp $passwd;
	
	if ( lc($passwd) eq 'q') {
		print "CRL generation skipped.\n";
		exit 1;
	} else {
		# Then generate the CRL
		print "Now generating the CRL, please wait ...\n";
		$ua = LWP::UserAgent->new();
		my $req = POST 'http://'.$hostname.$CRLURL.'',
			[ cmd => 'genCRL',
			  passwd => $passwd,
			  passwd_dialog_mode => '',
			  days => $CRLLifeDays,
			];
		$content = $ua->request($req)->as_string;
		# print $content;
	
		if ($content =~ /Making CRL available on server/) {
			$CRL = 1;
			print "\tCRL generation successful.\n";
	
	        # Now export the CRL
			print "Now exporting CRL, please wait ...\n";
			$ua = LWP::UserAgent->new();
			my $url = POST 'http://'.$hostname.$exportURL.'',
					[ cmd => nodeEnrollCRL,
					];
			$content = $ua->request($url)->as_string;
			if ($content =~ /Archive created successfully/) {
				print "\tExport successful.\n";
				exit 0;
			} else {
				print "\tExport failed.\n";
				exit 1;
			}
	
		} else {
			print "\tCRL generation failed (re-try or skip).\n";
		}
	}

} # End while not $CRL
1;


