#!/usr/bin/perl


use strict;

my $version = "0.2";

my $onemonth = 30 * 24 * 60 * 60;  # 30 days of seconds
my $oneday = 24 * 60 * 60;   # one day of seconds
my $OPENSSL = "openssl x509 -text  -noout -in ";


use Date::Manip;
use Time::Local;


#my $string = '18-Sep-2008 20:09'; # or a wide range of other date formats
#my $unix_time = UnixDate( ParseDate($string), "%s" );
#printf("E: %d\n",$unix_time);

my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);

my %Action;
my %Server;
my %Notify;

# current time in epoch
my $timenow = time();


my $line;
while ($line = <DATA> ) {
    chomp($line);
    next if (length($line) <= 0 );
    next if ($line =~ m/^[ 	]*#/);
    my ($cert, $action, $server) = split(' ',$line);
    $Action{$cert} = $action;
    $Notify{$cert} = $action;
    $Server{$cert} = $server;
    open(CERT,"$OPENSSL $cert | ") || die "can't read $cert";
    printf("=====\nCertficate: $cert\n");
    my $certline;
    while ($certline = <CERT>) {
	chomp($certline);
	if ($certline =~ m/before/ic) {
#	    printf("$certline\n");
	}
	if ($certline =~ m/after/ic) {
#	    Not After : Dec 21 04:12:57 2022 GMT
	    my ($start,$dateline) = split(':',$certline,2);
	    my $afterepoch = UnixDate( ParseDate($dateline), "%s" );
	    my $renewalepoch = $afterepoch - $onemonth;


#	    printf("$certline ->$dateline<- ->$afterepoch<-->$timenow<-\n");
	    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($renewalepoch);
	    $year = $year + 1900;

	    printf("$certline\n");

	    printf("\trenewal on %s-%s-%s at %02d:%02d (local) \n",$year,$abbr[$mon],$mday,$hour,$min);

	    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($renewalepoch);
	    $year = $year + 1900;
	    printf("\trenewal on %s-%s-%s at %02d:%02d (GMT) \n",$year,$abbr[$mon],$mday,$hour,$min);

	    my $renewaldaysfromnow = int (($renewalepoch - $timenow) / $oneday);
            printf("\t  %d days from now\n",$renewaldaysfromnow);


	}
	if ($certline =~ m/CN/ic) {
	    printf("$certline\n");
	}
	if ($certline =~ m/DNS/ic) {
	    printf("$certline\n");
	}
    }
    close(CERT);
}





__DATA__
# a comment
#/etc/letsencrypt/live/w5gfe.org/cert.pem  bw@w5gfe.org apache
## another comment
#./cert.pem bw@okiefrog.org nginx
# blank line follows
/usr/local/G1/OKIECERTS/CERTS/w5gfe-cert.pem bw@w5gfe.org nginx
/usr/local/G1/OKIECERTS/CERTS/okiefrog-cert.pem bw@okiefrog.org nginx

# end of blank line

