#!/usr/bin/perl

# Copyright (C) 2008 NEC Corporation
# All Rights Reserved. 

# RCS: $Id: wbmc_timer,v 1.2 2010/04/26 11:04:27 wbmc Exp $

#2008/09 higashi
#readFileؿѤ뤿ɤ߹
require "/opt/nec/wbmc/lib/wbmc.pl";

#2008/08 higashi
#ϴؿɤ߹
require "/opt/nec/wbmc/bin/time_conv.pl";

#2008/09 higashi
#ޡƻԤžλ֤žޥ
#򵭽Ҥե(tmp_time)ؤΥѥ
$time_path = "/var/log/accesslog_transfer/tmp_time";
$time_path_lock = "tmp_time";

#2008/09 higashi
#accesslog_transfer.logơȤ륵
$accesslog_transfer_log_rotate_size=5242880;

#2008/10 higashi
#žΥϤեؤΥѥ
$accesslog_transfer_log_path = "/var/log/accesslog_transfer/accesslog_transfer.log";

@timeout_file=();
#2008/09 higashi
#time_logʤнλ
if(-e $time_path){
	#2008/09 higashi
	#եɤ߹ߥå
	if(!&readFile($time_path,$time_path_lock,*timeout_file)){
		system("/bin/echo $time_path cannot read");
		if(!&writeLog_rotate("[Error] $time_path cannot read",$accesslog_transfer_log_path,"wbmc_timer",$accesslog_transfer_log_rotate_size)){
			system("/bin/echo $accesslog_transfer_log_path cannot write");
		}
		exit(1);
	}
	#2008/09 higashi
	#time_logͤǼѿν
	$log_file_name="";
	$time_end="";
	$log_send_proces="";

	for($i=0;$i < @timeout_file;$i++){
		#2008/09 higashi
		#žΥե̾
		if($timeout_file[$i] =~ /^\s*FILE_NAME=\s*(.*)\s*$/){
			$log_file_name = $1;
		}
		#2008/09 higashi
		#λ֤
		if($timeout_file[$i] =~ /^\s*END_TIME=\s*(\d*)\s*$/){
			$time_end = $1;
		}
		#2008/09 higashi
		#ž
	        if($timeout_file[$i] =~ /^\s*PROCESS=\s*(.*)\s*$/){
			$log_send_proces = $1;
		}
	}

	#2008/09 higashi
	#ͤǤå
	if($log_file_name eq ""){
		if(!&writeLog_rotate("[Error] The file path is not set",$accesslog_transfer_log_path,"wbmc_timer",$accesslog_transfer_log_rotate_size)){
			system("/bin/echo $accesslog_transfer_log_path cannot write");
		}
		exit(1);
	}

	#2008/09 higashi
	#λ֤ʤäǥեȤ	
        if($time_end eq ""){
		if(!&writeLog_rotate("[Error] The time-out is not set",$accesslog_transfer_log_path,"wbmc_timer",$accesslog_transfer_log_rotate_size)){
			system("/bin/echo $accesslog_transfer_log_path cannot write");
		}
		exit(1);
	}
        if($log_send_proces eq ""){
		if(!&writeLog_rotate("[Error] The process is not set",$accesslog_transfer_log_path,"wbmc_timer",$accesslog_transfer_log_rotate_size)){
			system("/bin/echo $accesslog_transfer_log_path cannot write");
		}
		exit(1);
	}

	#2008/09 higashi
	#߻֤UTC(1970/01/01ÿ)Ǽ
	$time_now = `date +%s`;

	#2008/09 higashi
	#žե뤬Ƥ뤫ॢȤλ֤᤮Ƥ
	#žץkill
	if(!(-e $log_file_name) || ($time_now >= $time_end)){
		open(IN,"/bin/ps -efw |");
		while(<IN>){
			if($_ =~ /\s*$log_send_proces\s*$/){
				@wk = split(/\s+/, $_);
				system("/bin/kill $wk[1]");
				if($time_now >= $time_end){
					if(!&writeLog_rotate("[Warning] The accesslog transfer did the time-out",$accesslog_transfer_log_path,"wbmc_timer",$accesslog_transfer_log_rotate_size)){
						system("/bin/echo $accesslog_transfer_log_path cannot write");
					}
				}
			}
		}
		if(-e $time_path){
			system("/bin/rm -r $time_path > /dev/null 2>&1");
		}
	}
}
