#!/usr/bin/perl
# Copyright (C) 2000 NEC Corporation
# All Rights Reserved.

# RCS: $Id: wbmc_certificate,v 1.1 2006/12/22 05:28:48 shodai Exp $

# κȯԥޥ

use POSIX;
require "/opt/nec/wbmc/lib/cert.pl";

$crt = "/etc/opt/nec/wbmchttpd/conf/ssl.crt/server.crt";
$ret = 0;

# ߻μ
$date_now = time();

# ͭ¤μ
if (&getnotAfter($crt, *str_notafter)) {
	$ret = -1;
	goto done;
}
if (&getnotBefore($crt, *str_notbefore)) {
	$ret = -1;
	goto done;
}

# ǯʬäʬ
&str2date($str_notafter, *year, *mon, *day, *hour, *min, *sec);
&str2date($str_notbefore, *year2, *mon2, *day2, *hour2, *min2, *sec2);

# ÿѴ
$not_after = POSIX::mktime($sec, $min, $hour, $day, $mon, $year);
$not_before = POSIX::mktime($sec2, $min2, $hour2, $day2, $mon2, $year2);

# ͭ¤Σ᤮Ƥȯ
# (not after - not before) * 0.7  not before  ­ͤ
# ߻Τۤ礭硢ȯ
$tmp_time = int(($not_after - $not_before) * 0.7);
$mkcert_time = $not_before + $tmp_time;

if ($date_now >= $mkcert_time) {
	#
	# ȯ
	#
	if(!&make_cert()) {
		$ret = -1;
		goto done;
	}
}

done:
	exit($ret);

#------------------------------------------------

# notAfter 
sub getnotAfter {
	local($crt, *str_notafter) = @_;
	local($tmp);

	if (!open CMD, "/usr/bin/openssl x509 -in $crt -enddate -noout|")
	{
		$ret = -1;
		goto done;
	}

	@tmp = <CMD>;
	close(CMD);

	$str_notafter = $tmp[0];

done:
	return($ret);
}

# notBefore 
sub getnotBefore {
	local($crt, *str_notbefore) = @_;
	local($tmp);

	if (!open CMD, "/usr/bin/openssl x509 -in $crt -startdate -noout|")
	{
		$ret = -1;
		goto done;
	}

	@tmp = <CMD>;
	close(CMD);

	$str_notbefore = $tmp[0];

done:
	return($ret);
}

# ʸ󤫤ǯʬäѴ
# mon 0 = 11
# year 1900 -> 0 , 2000 -> 100
sub str2date {
	local($str, *year, *mon, *day, *hour, *min, *sec) = @_;
	local(@ent);

	$str =~ s/^\s+//;
	@ent = split(/[\s=:]+/, $str);

	$year = sprintf("%03d", $ent[6] - 1900);
	$day  = sprintf("%02d", $ent[2]);
	$hour = sprintf("%02d", $ent[3]);
	$min  = sprintf("%02d", $ent[4]);
	$sec  = sprintf("%02d", $ent[5]);

	$mon  = sprintf("%02d", &month_str2int($ent[1]));
}

# ʸѴ
# ֤ͤ 0-11 
# sub month_str2int();
# 㡧Jan --> 0
#     Dec --> 11
sub month_str2int
{
	local($str) = @_;

	if ($str =~ /Jan/i) {
		$ret = 0;
	} elsif ($str =~ /Feb/i) {
	    	$ret = 1;
	} elsif ($str =~ /Mar/i) {
		$ret = 2;
	} elsif ($str =~ /Apr/i) {
		$ret = 3;
	} elsif ($str =~ /May/i) {
		$ret = 4;
	} elsif ($str =~ /Jun/i) {
		$ret = 5;
	} elsif ($str =~ /Jul/i) {
		$ret = 6;
	} elsif ($str =~ /Aug/i) {
		$ret = 7;
	} elsif ($str =~ /Sep/i) {
		$ret = 8;
	} elsif ($str =~ /Oct/i) {
		$ret = 9;
	} elsif ($str =~ /Nov/i) {
		$ret = 10;
	} elsif ($str =~ /Dec/i) {
		$ret = 11;
	} else {
		$ret = -1;
	}

	return($ret);
}
