#!/usr/local/bin/perl

use strict;
use vars qw($opt_p $opt_n $opt_bench $opt_debug $opt_version $opt_v);
#use lib qw(lib);
use Net::SSL;
use File::Basename;
use Benchmark;

use Getopt::Long;
&GetOptions ('p:s' => \$opt_p, 
	     'proxy:s' => \$opt_p, 
	     'bench:n' => $opt_bench,
	     'd' => \$opt_debug,
	     'version:i' => \$opt_version,
	     'v:i' => \$opt_version,
	     );
if($opt_debug) {
    eval "use LWP::Debug qw(+)";
}

my $basename = &File::Basename::basename($0);
my $method = (@ARGV && $ARGV[0] =~ /^[A-Z]+$/) ? shift : "HEAD";
my $host;
if($opt_bench) {
    $host = shift || die("need host, run like ./$basename HEAD yourhost.com.foo");
} else {
    $host = shift || "www.nodeworks.com";
}
my $port   = shift || 443;

if($opt_p) {
    $ENV{HTTPS_PROXY} = $opt_p;
}
if($opt_n) {
    $ENV{NO_PROXY} = $opt_n;
}

if($opt_version) {
    grep($opt_version eq $_, '2', '3', '23')
	|| die("$opt_version must be one of 2, 3, or 23");
    $ENV{HTTPS_VERSION} = $opt_version;
}

unless(eval { &ssl_connect() }) {
    print <<OUT;
== FAILED TO CONNECT ==
Error: $@

If you need to use a proxy, please pass it in as an argument like  

  ./net_ssl_test -p 127.0.0.1:8080

which sets \$ENV{HTTPS_PROXY} for you.

OUT
    ;
}

if($opt_bench) {
    timethis($opt_bench, sub { &ssl_connect() });   
}
    

sub ssl_connect {
    my $sock = Net::SSL->new(
			     PeerAddr => $host,
			     PeerPort => $port,
			     SSL_Debug => $opt_debug,
			     ) || die "Can't connect to $host:$port, $!";
  
    my $out .= "WEB SITE: $host:$port\n";
    $out .= "CIPHER: ".$sock->get_cipher."\n";
    my $cert = $sock->get_peer_certificate;
    
    $out .= "THIS IS: ".$cert->subject_name."\n";
    $out .= "CERTIFIED BY: ".$cert->issuer_name."\n";
    $out .= "\n";
    
    $sock->print("$method / HTTP/1.0\n\n");
    
    my $buf = '';
    while ($sock->read($buf, 1024)) {
	$out .= $buf;
    }

    unless($opt_bench) {
	print $out;
    }

    1;
}

