# Check whether there are incomplete restorereplica processes in progress

use English;
$usage = "Usage:
<path-to-Perl> $PROGRAM_NAME 				scan current VOB
<path-to-Perl> $PROGRAM_NAME <vobtag>		scan specified VOB
<path-to-Perl> $PROGRAM_NAME -all			scan all VOBs in region
<path-to-Perl> $PROGRAM_NAME -host			scan all VOBs on this host
<path-to-Perl> $PROGRAM_NAME -host <hostname>	scan all VOBs on named host
";
die $usage if (grep(/^$ARGV[0]$/i,("-?","-help","-h","-usage")));

die ("This script must be run on a host with ClearCase MultiSite installed\n")
	if system("multitool","-version");
system("cleartool","hostinfo");

#
# Determine which VOBs to scan.
#
$format = $ARGV[0];
if ("-short" =~ /$format/i) {
   $long_format = "n";
   shift(@ARGV);
}
if ("-long" =~ /$format/i) {
   $long_format = "y";
   shift(@ARGV);
}


@vobtag_list = (@ARGV == 0 ? `cleartool desc -s vob:.` : @ARGV);
if ($vobtag_list[0] eq "-all") {
	@vobtag_list = `cleartool lsvob -s`;
}
if ($vobtag_list[0] eq "-host") {
	$host = (@vobtag_list == 2 ? $vobtag_list[1] : `hostname`);
	@vobtag_list = `cleartool lsvob -s -host $host`;
}
chomp @vobtag_list;

foreach $vobtag (@vobtag_list) {
	&check_vob($vobtag);
}


sub check_vob {
	my $vobtag = $_[0];
	my ($replica,@replica_list,@output);

	#
	# Get list of replicas, including deleted ones.
	#
	($replica) = `multitool lsreplica -s -invob $vobtag`;
	chomp ($replica);
	@output = `multitool lsepoch $replica\@$vobtag`;
	@replica_list = grep(s/.*\((.*)\)$/$1/,@output);
	chomp @replica_list;

	#
	# Check each replica for restorereplica oplog entry.
	#
	foreach $replica (@replica_list) {
		@output = `multitool dumpoplog -invob $vobtag -vreplica $replica -long -name -from 0xFFFFFFFF`;
		print "Checking $replica\@$vobtag\n";
		if (@output > 0) {
			print "restorereplica oplog found for replica $replica\@$vobtag\nGet related oplogs? [y] ";
			my $reply = $long_format eq "" ? <STDIN> : $long_format ;
			if ($reply =~ /^n/i) {
				print @output;
			}
			else {
				#
				# Dump all restorereplica related oplog entries created since the found restorereplica.
				# - Take the oplog table entry number from the dumped entry
				# - dump in short format to the end of the table and filter on /op=*restore*/
				# - dump in long format for any that match
				#
				for ($i=0; $output[$i]!~s/^(\d+):$/$1/; $i++) {
					die "oplog table entry number not found" if $i >= @output;
				}
				@output = `multitool dumpoplog -invob $vobtag -short -from $output[$i]`;
				foreach $oplog (@output) {
					next unless $oplog =~ s/^(\d+): op=.*restore.* rep=.* id=\d+/$1/;
					system("multitool dumpoplog -invob $vobtag -long -name $oplog");
				}
			}
		}
	}
}

