## OpenCA - Command
## (c) 1998-2002 by OpenCA Group
##
##   File Name: warnExpiring
##       Brief: warn users if their cert expires
## Description: warn users if their certificate expires in the
##              configured time
##  Parameters:

## highly experimental actually and not linked to any webinterface

sub cmdWarnExpiring {

    my $now = time;
    ## 86400 is one day
    my $advance = 30;
    my $limit = $now + $advance*86400;

    use Time::Local;
    use MIME::Lite;
    use MIME::Words qw(:all);

    my $cert = $db->getNextItem( DATATYPE=>'VALID_CERTIFICATE', KEY=>-1 );

    $DEBUG = 1;

    ## Process all Files
    while ( $cert ) {

        my $key  = $cert->getSerial();
        print "Seen certificate with key $key<br>\n" if $DEBUG;

        my $email   = $cert->getParsed()->{EMAILADDRESS};
        my $cn      = $cert->getParsed()->{DN_HASH}->{CN}[0];
        my $expires = $cert->getParsed()->{NOTAFTER};

        my $expire_date = $cryptoShell->getNumericDate($expires);
        my ($yyyy,$mm,$dd,$HH,$MM,$SS) =
            ( $expire_date =~ m/(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ );

        printf "Parsed expire date %d-%d-%d %d:%d<br>\n",
               $yyyy, $mm, $dd, $HH, $MM, $SS if $DEBUG;
        my $expiry_ts = timegm($SS,$MM,$HH,$dd,$mm-1,$yyyy-1900);
	
        print "cert:$key<br>now:$now<br>expires at:$expire_date<br>in seconds:$expiry_ts<br>\n" if $DEBUG;
        if ( $expiry_ts < $now ) {
            printf "CA %s: %s (%s) expired since %s|!!<br>\n",
                   $ca, $key, $email, $printable_date;

         } elsif ( $expiry_ts < $limit ) {
            printf "CA %s: %s (%s) expires at %s!!!<br>\n",
                   $ca, $key, $email, $printable_date;
            my $text = "This is a mail and normally I'm configured in ra.conf";

            my $msg = MIME::Lite->new(
                          From    =>encode_mimewords("Servicio de Certificados")." <camanager\@stl.es>",
                          To      =>encode_mimewords($cn)." <$email>",
                          Subject =>encode_mimewords("Prxima caducidad del certificado para $email ($key)"),
                          Type    =>'TEXT',
                          Encoding =>'8bit',
                          Data    =>$text
                                     );
            $msg->attr("content-type.charset" => "ISO-8859-1");

            ## this is normally a pipe to a mailprogram
            print $msg->print();

        } else {
            print "nothing to do<br>\n";
        }

	    print "Certificate for $email expires on $expire_date<br>\n" if $DEBUG;

    	$cert = $db->getNextItem( DATATYPE=>'VALID_CERTIFICATE', KEY=>$key );
    }
    return 1;
}

1;
