#!/usr/bin/perl -I/usr/local/teamfile/tfsplugin/lib/perl
#
# Operation log index builder.
#
use strict;
use utf8;
use Getopt::Long;
use TF::OplogIndex;

require "/usr/local/teamfile/www/bin/mt-lib.pl";

my $LOCK_FILE = getLogPath() . '/oplogindexer.pid';
my $LOG_FILE  = getJobsWorkPath() . '/oplogindexer.log';
my $F_LOG     = undef;
my $opt_h     = undef;
my $opt_v     = undef;

my $ret = GetOptions("h" => \$opt_h, "v" => \$opt_v);
if ($opt_h) {
	usage();
	exit(0);
}

exit(main());

sub main {
	my $cRetry = 0;
	while (!isRunning(getApachePidPath())) {
		sleep 1;
		if ($cRetry++ >= 30) {
			printerr("Apache had been stopped. we give up execution of oplog indexer.\n");
			exit(1);
		}
	}

	if ((my $pid = lockScript($LOCK_FILE)) != 0) {
		printerr("This script had been already started by $pid.\n");
		return 1;
	}

	initLog();

	my %gparams = readTfGlobalSettings();
	$cRetry = 0;
	while (isRunning($gparams{DAILYBAT_LOOKFILE})) {
		sleep 1;
		if ($cRetry++ >= 600) {
			writeLog("The backup script is running. skipped.");
			closeLog();
			unlockScript($LOCK_FILE);
			return 0;
		}
	}

	my $log_root = getLogPath();
	my $date = TF::OplogIndex::next_unindexed_date($log_root);
	if (!$date) {
		writeLog("No unindexed access log.");
		closeLog();
		unlockScript($LOCK_FILE);
		return 0;
	}

	writeLog("Start indexing access_log.$date.");
	my $ok = TF::OplogIndex::build_day_index($log_root, $date);
	if ($ok) {
		writeLog("Finished indexing access_log.$date.");
	}
	else {
		writeLog("Failed or skipped indexing access_log.$date.");
	}

	closeLog();
	unlockScript($LOCK_FILE);
	return $ok ? 0 : 1;
}

sub usage {
	print <<"_EOF_";
Usage: oplogindexer [-v] | [-h]
       -v : Show detail status
       -h : Show usage
_EOF_
}

sub printerr {
	my $msg = shift || '';
	print STDERR $msg if $opt_v && $msg;
}

sub initLog {
	open $F_LOG, ">", $LOG_FILE;
}

sub writeLog {
	my $msg = shift || '';
	return if !$msg;
	my $ctime = localtime(time);
	print $F_LOG $ctime . ' : ' . $msg . "\n" if $F_LOG;
	printerr($msg . "\n");
}

sub closeLog {
	close $F_LOG if $F_LOG;
}
