#! /usr/bin/perl

use strict ;
use warnings ;

my %PORTS = ( http => 443 , ldap => 636 ) ;
my $PORTS = join ',', sort keys %PORTS ;

my $prog = substr $0, rindex ( $0, '/' ) + 1 ;
my $Usage = <<USAGE ;
Usage: $prog [-v] [-q] [-d] host port [servername]
option v : be verbose
option q : be quiet
option d : show debug info
argument port : numeric or one of [$PORTS]
argument servername : optional ; required for MS-iis
USAGE
sub Usage { die "$_[0]$Usage" ; }
sub Error { die "[error] $prog: $_[0]\n" ; }
sub Warn  { warn "[warn] $prog: $_[0]\n" ; }

# usage: &GetOptions(ARG,ARG,..) defines $opt_ID as 1 or user spec'ed value
# usage: &GetOptions(\%opt,ARG,ARG,..) defines $opt{ID} as 1 or user value
# ARG = 'ID' | 'ID=SPC' | 'ID:SPC' for no-arg, required-arg or optional-arg
# ID  = perl identifier
# SPC = i|f|s for integer, fixedpoint real or string argument

use Getopt::Long ;
Getopt::Long::config ( 'no_ignore_case' ) ;
my %opt = () ; Usage '' unless GetOptions
  ( \%opt, qw(v q d f) ) ;
Usage("Arg count\n") unless @ARGV == 2 or @ARGV == 3 ;

$opt{v} ||= $opt{d} ;

my $HOST = shift ;
my $PORT = shift ; $PORT = $PORTS { $PORT } if $PORTS { $PORT } ;
my $SNAM = shift ;
Error "bad port [$PORT]" unless grep $_ eq $PORT, values %PORTS ;

unless ( $opt{v} ) { open STDERR, '>', '/dev/null' ; }

my $CMD =
  ( "openssl s_client -connect $HOST:$PORT"
  . ( $SNAM ? " -servername $SNAM" : '' )
  . ' < /dev/null'
  . ' |'
  . ' openssl x509 -noout -dates'
  ) ;

print "$CMD\n" if $opt{v} ;
open CMD, '-|', $CMD or Error "can't popen $CMD" ;
my @lines = <CMD> ;
close CMD ;
Error "no lines" unless @lines ;
print @lines if $opt{v} ;

my $line = ( grep /^notAfter=/, @lines ) [ 0 ] ;
$line =~ s/^notAfter=// ;
print $line ;
