#!/usr/bin/perl

# $Id: //depot/cad/tools/1.0/icp4-1.1/bin/p4co#5 $
#
# CSWITCH CORPORATION CONFIDENTIAL PROPRIETARY
# 
# This file contains information which is the
# proprietary property of Cswitch Corporation.
# This file is confidential and its contents may
# not be disclosed without the expressed written
# consent of Cswitch Corporation.


use strict;
use warnings;

use FindBin qw($Bin);
use lib "$Bin/../lib";

use Icp4;
use Getopt::Std;
use File::Basename;

our (%opt, $Program, $islayout);

MAIN: {

    my($cell, $cell_dirname);
    $Program = $FindBin::Script;

    getopts('hDn', \%opt);

    if ($opt{h} || $#ARGV < 0) {
	print "Usage: $Program [-h] [-n] cell\n";
	print "   -h: help usage\n";
	print "   -n: show operation only\n";
	print " cell: cell name)\n";
	exit;
    }

    $islayout = &Icp4::is_layout_view();

    my $bad = 0;
    foreach $cell (@ARGV) {
	$cell_dirname = $cell;
	if ($cell =~ /\$/) {
	    $cell =~ s/\$/\\\$/g;
	}

	if (!-d $cell_dirname) {
	    print "WARNING: cell \"$cell\" not found\n";
	    $bad = 1;
	    next;
	}
	if (!&sync_check($cell)) {
	    print "INFO: Cell \"${cell}\" is out of date, please sync.  Cell not checked out.\n";
	    $bad = 1;
	    next;
	}

#	if ($islayout) {
#	    print "INFO: Checking out (\"p4 edit ${cell}/...\")\n";
#	} else {
#	    print "INFO: Checking out (\"p4 edit ${cell}.* ${cell}/...\")\n";
#	}

	print "INFO: Checking out \"$cell\"\n";

	next if $opt{n};

	if ($islayout) {
	    system "p4 edit ${cell}/...";
	} else {
	    system "p4 edit ${cell}.* ${cell}/...";
	}
	# TODO check "system" return code
    }

    exit $bad;
}

sub sync_check {
    my($cell) = @_;
    print "INFO: Checking for latest version of \"$cell\"\n";
    if ($islayout) {
	#print "INFO: Checking for latest versions (\"p4 sync -n ${cell}/...\")\n";
	open (P4, "p4 sync -n ${cell}/... |");
    } else {
	#print "INFO: Checking for latest versions (\"p4 sync -n ${cell}.* ${cell}/...\")\n";
	open (P4, "p4 sync -n ${cell}.* ${cell}/... |");
    }
    while (<P4>) {
	if (/- added /) {
	    return 0;
	}
	if (/- updating /) {
	    return 0;
	}
	if (/- deleted /) {
	    return 0;
	}
    }
    return 1;
}