#!/usr/bin/perl

# Delete a p4 controlled cell or view


$lib=$ARGV[0];
$client=$ARGV[1];
$path=$ARGV[2];
$type=$ARGV[3];

if($#ARGV<3) {
    die("Usage: deleteCellOrView.pl libname clientname pathname cell|view\n");
}


local($p4) = "p4";

# First get all the opened files

$dlist=0;
$wrotecl=0;
open(CL, ">/tmp/p4cl.$$") || die "Couldn't open /tmp/p4cl.$$" ;

print(CL "\nChange: new\n\Description: $type delete\n\n\nFiles:\n\t");

if($type eq "cell") {
    open(OPENED, "$p4 -c $client opened $path/\*/\*|") || next;
}

if($type eq "view") {
    open(OPENED, "$p4 -c $client opened $path/\*|") || next;
}

if($type eq "file") {
    open(OPENED, "$p4 -c $client opened $path|") || next;
}



while(<OPENED>) {

    {
	# is it add or edit
	(@mode)=split;
	($depotfile)=split('#', $mode[0]);
	$p4mode=$mode[2];
	
	
	if($p4mode eq "add") {
	    # revert it
	    system("$p4 -c $client revert $depotfile");
	    $dlist{$depotfile}=1;
	    next;
	}

	if($p4mode eq "delete") {
	    print(CL "\t$depotfile\n");
	    $wrotecl++;
	    $dlist{$depotfile}=1;
	    next;
	}


	if($p4mode eq "edit") {
	    # mark it for delete
	    # write it into the change list
	    system("$p4 -c $client revert $depotfile; $p4 -c $client delete $depotfile");
	    print(CL "\t$depotfile\n");
	    $wrotecl++;
	    $dlist{$depotfile}=1;
	    next;
	}
	
    }
}

close(OPENED);


if($type eq "cell") {
    open(HAVE, "$p4 -c $client have $path/\*/\*|") || next;
}

if($type eq "view") {
    open(HAVE, "$p4 -c $client have $path/\*|") || next;
}

if($type eq "file") {
    open(HAVE, "$p4 -c $client have $path|") || next;
}


while(<HAVE>) {

    {

	($depotfilev)=split;
	($depotfile)=split('#', $depotfilev);

	if($dlist{$depotfile} eq 1) {
	    #print "Skipping $depotfile\n";
	    next;
	}
	
	system("$p4 -c $client delete $depotfile");
	print(CL "\t$depotfile\n");
	$wrotecl++;
    }
}


print (CL "\n");
close(CL);

# submit the changelist

if($wrotecl) {
    system("$p4 -c $client submit -i < /tmp/p4cl.$$");
}

system("rm /tmp/p4cl.$$")