#!/usr/bin/perl

# $Id: //depot/cad/tools/1.0/icp4-1.1/bin/p4ls#3 $
#
# 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;
use Cwd;

our (%opt, $Program);

# get_filelist --
#	returns a list of files
sub get_filelist {
    my($dir) = @_;
    my(@files) = ();

    open(FIND, "find $dir -type f -print |");
    while (<FIND>) {
	chomp;
	push (@files, $_);
    }
    return(@files);
}


MAIN: {

    my(@bits, $file, $type);
    my($prot, $id, $user, $group, $size, $month, $day, $time);
    my($absFile);
    my(%p4files);
    my(@files) = ();

    $Program = $FindBin::Script;

    getopts('DhR', \%opt);

    if ($opt{h}) {
	print "Usage: $Program [-h] [-R] [input]+\n";
	print "   -h: help usage\n";
	print "   -R: recursive\n";
	print "input: directory\n";
	exit;
    }

    $Icp4::debug = ($opt{D}) ? 1 : 0 ;

    if (scalar(@ARGV) == 0) {
	$ARGV[0] = '.';
    }
    foreach $file (@ARGV) {
	if (-d $file) {
	    if ($opt{R}) {
		push(@files, &get_filelist($file));
	    } else {
		push(@files, glob("$file/*"));
	    }
	} else {
	    push(@files, $file);
	}
    }
    my($files) = join(' ', @files);
    if ($opt{D}) {
	foreach $file (@files) {
	    print "$file\n";
	}
    }

    # get a list of files.

    # make sure p4 is configured
    if (&Icp4::where() eq 'error') {
	printf(STDERR "ERROR: Current directory not in client. Check P4 variables.\n");
	printf(STDERR "       No Perforce information available.\n");
	exit -1;
    }

    # get the p4 status of the files.
    %p4files = Icp4::fstat(@files);

    open(LS,"/bin/ls -ld $files|") or die "ERROR: Couldn't run 'ls -ld'";
    while (<LS>) {
	# print $_;
  	if (/^total/) {
	    print $_;
  	    next;
  	}
  	chomp;
  	($prot, $id, $user, $group, $size, $month, $day, $time, $file) = split;
  	if ($file =~ /\#/) {
  	    $type = "???";
  	} else {
	    $absFile = Cwd::abs_path(dirname($file)) . '/' .  basename($file);
	    printf(STDERR "DEBUG: %s\n", $absFile) if ($opt{D});
  	    if (! defined($p4files{$absFile})) {
		$type = '???';
	    } else {
		$type = $p4files{$absFile};
	    }
  	}
	printf("%-10s  %2d %7s %6s %5s %8d %3s %2s %4s %s\n",
	       $prot, $id, $user, $group, $type, $size,
	       $month, $day, $time, $file);
    }
    close(LS);

    exit 0;
}