#!/usr/bin/perl

# Clean up old workspaces

# We want to sync #none/client delete to reduce db and local disk usage

# remember p4 is server centric

$ws=$ARGV[0];


if(!$ws) {
    print "Usage: wsclean <workspace directory>\n";
    exit(1);
}
$user=$ENV{USER};

$noclean=0;
$reject=0;

# look for a cds.p4client
$cfile="$ws/cds.p4client";

open(WS,"<$cfile") || die "Could not read $cfile\n";

while(<WS>) {

    if(/^#/) {
       next;
   }
    
    chop;
    (@data)=split;
    $client=$data[2];
    # Check the syntax
    (@cdata)=split(':',$client);
    if( $cdata[2] eq "") {
	print "Reject non-user client $client\n";
	$reject=1;
	next;
    }
    print "Checking client $client\n";
    $cmd="p4 -c $client opened";
    open(CMD,"$cmd 2>&1|") || die "Could not run $cmd\n";
    while(<CMD>) {
	if(/change/) {
	    print;
	    print "Checkouts detected, no cleanup will take place!\n";
	    $noclean=1;
	    $reject=1;
	}
	else {
	    push(@clist,$client);
	}
    }
}

if($noclean eq 0 && $reject ne 1) {
    print "Cleaning data\n";
    foreach $cl (@clist) {
	print "Emptying client $cl\n";
	$cmd="p4 -c $cl sync \\#none > /dev/null";
	print "$cmd\n";
	system($cmd);
	$cmd="p4 client -d $cl";
	system($cmd);
    }
}
if($reject ne 1) {
    print "Deleting directory $ws\n";
    system("rm -rf $ws");
}