#!/usr/bin/perl -w

use strict;
use warnings;
use Crypt::OpenSSL::X509;
use Date::Parse;
use Getopt::Long;
use JSON;

my $index = '/opt/phpki/phpki-store/CA/index.txt';
my $path = '/opt/phpki/phpki-store/CA/newcerts';

GetOptions(
    "index=s" => \$index,
    "path=s"  => \$path
);

open INDEX, "$index" or die "Couldn't open $index\n";

my $json;

foreach my $l (<INDEX>){
    next unless $l =~ m/^([VR])\t\d+Z\t(\d+Z)?\t(\w+)\tunknown\t.*/;
    my $status = $1;
    my $serial = $3;
    my $cert = Crypt::OpenSSL::X509->new_from_file( "$path/$serial.pem" );

    my $expire_in = int ((str2time($cert->notAfter())-time())/(3600*24));
    if ($status eq 'V'){
        $status = 'valid';
    }
    elsif ($expire_in lt 0){
        $status = 'expired';
    }
    else{
        $status = 'revoked';
    }
    my $subject = $cert->subject;
    $subject =~ m/.*\sCN=(.*),/;
    my $cn = $1;

    push @{$json->{data}}, {
          "{#CRTCN}" => $cn,
          "{#CRTSERIAL}" => $serial,
          "{#CRTSTATUS}" => $status,
    };
}
close INDEX;
print to_json($json);
