#!/usr/local/bin/perl

use File::stat;
use Time::localtime;

use Getopt::Long;

$Getopt::Long::autoabbrev=0; 

unless($result=GetOptions("h", "bname=s",
			  "l")) {
    die "Illegal Input Options, -h for help\n";
}

$HELP="Usage: cdscheckouts -bname <branch_name> [-l]
Long format will stat each file\nto give modify time\nand can take a few moments\n";


if($opt_h) {
    print $HELP;
    exit;
}
    
if(!$opt_bname) {
	print $HELP;
	exit;
}
	

$cmd="p4 branches | grep $opt_bname > /dev/null";
system($cmd);

if($? ne 0) {
  print "Couldn't find branch $opt_bname\n";
  exit 1;
  }

    
print "Getting check out status...please wait\n";


$cmd="p4 opened -a //depot/$opt_bname/...| grep cdb > /tmp/p4cdsco.$$";


system($cmd);

open(CMD,"</tmp/p4cdsco.$$") || die;


while(<CMD>) {
    
    chop;
    (@data)=split;

    ($user,$client)=split('@',$data[7]);
    ($nclient,$branch)=split(':',$client);

    (@dspec)=split('/',$data[0]);

    $max=($#dspec);
    $datastring="$user $dspec[$max-3] $dspec[$max-2]";
    $dlen=length($datastring);
    $numspaces=40-$dlen;
    $pad="";
    for $i (0...$numspaces) {
	$pad=$pad." ";
    }
    $datastring=$datastring.$pad.$dspec[$max-1];

    
    # target column 50 for beginning of data field
    $dlen=length($datastring);
    $numspaces=50-$dlen;
    $pad="";
    for $i (0...$numspaces) {
	$pad=$pad." ";
    }
    $datastring=$datastring.$pad.$data[2];




    if($opt_l) {
	# if modtime is set in the client
	# we can see the time the file was last modified
	(@dfilenorev)=split('#',$data[0]);
	
	$cmd="p4 -c $client have $dfilenorev[0]";
	open(CMD2,"$cmd 2>&1|") || die;
	while(<CMD2>) {
	    chop;
	    if(/not on client/) {
		    $date_string= "No data ($client)";    
		next;
		
	    }
	    ($ig,$ig,$unixpath)=split;
	    $date_string = ctime(stat($unixpath)->mtime());
	}
    

    
    
    $dlen=length($datastring);
    # target column 60 for beginning of data field
    $numspaces=60-$dlen;
    $pad="";
    for $i (0...$numspaces) {
	$pad=$pad." ";
    }
	$datastring=$datastring.$pad.$date_string;
    }
    $cotable{$branch}=$cotable{$branch}."\n".$datastring;

}

close(CMD);

foreach $key (sort(keys(%cotable))) {

    print "\nBranch: $key\n-------------------------------------------\n$cotable{$key}\n";
}



system("rm /tmp/p4cdsco.$$");