#!/usr/bin/perl

sub get_log_file {
	open(CONF,"</etc/syncfiles.conf");
	foreach(<CONF>) {
		if (m/^LOGFILE=(.*)$/) {
			close(CONF);
			return $1;
		}
	}
	close(CONF);
	return -1;
}

sub get_last_pos {
	return 0 if (! -f "/tmp/check-syncfiles.tmp");

	open(F,"</tmp/check-syncfiles.tmp");
	$value = <F>;
	close(F);
	chomp($value);
	return $value;
}

sub store_pos {
	$pos = shift;
	open(F,">/tmp/check-syncfiles.tmp");
	print F $pos;
        close(F);
}

sub main {

	$logfile = get_log_file();
	if ($logfile == -1) {
		print "UNKNOWN - Impossivel encontrar arquivo de log\n";
		exit 3;
	}

	$lastpos = get_last_pos();
	open(LOGFILE,"<$logfile");

	# verify if the file has been rotated
	seek(LOGFILE,0,2);
	$endfile = tell(LOGFILE);
	$lastpos = 0 if ($endfile < $lastpos);
	seek(LOGFILE,$lastpos,SEEK_SET);

	$critical = 0;
	foreach(<LOGFILE>) {
		if (m/^\[CRITICAL\].*/) {
			$critical=1;
		}
	}
	$lastpos = tell(LOGFILE);
	store_pos($lastpos);
	close(LOGFILE);

	if ($critical == 1) {
		print "CRITICAL - Erro encontrado no sincronismo, verificar\n";
		exit 2;
	}

	print "OK - Sem erros encontrados no sincronismo\n";
	exit 0;

}

main();
