#!perl -w

# Copyright (C) 1997 Capella Computers Ltd.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

# :FILE:
# Print depot files.

use strict;
use English;
use P4;

# Takes (optional) job id (or 'baseline') and (optional) file names.
sub usage {
    P4::crash("Usage: p4fp [<job>|baseline] <file-name>");
}

# Parse command line.
my $job;
if ($#ARGV < 0
 || $ARGV[0] eq '-h') {
    usage();
} elsif ($ARGV[0] =~ /^\d+$/
      || $ARGV[0] eq 'baseline') {
    $job = shift(@ARGV);
} else {
    $job = P4::current_job('baseline');
}

# If the user gave no arguments, specify all files.
if ($#ARGV < 0) {
    push(@ARGV, "...");
}

# No need to lock since this is (supposedly) a harmless read-only operation.

# Add appropriate prefix to file names.
my $prefix;
if ($job eq 'baseline') {
    # Prefix the baseline pattern to all specified files.
    $prefix = "//depot/baseline/";
} else {
    # Obtain job's record.
    my %record = P4::job_record($job);

    # Verify pre-conditions.
    my $status = $record{status};
    if ($status eq 'work') {
	# Developer trying to print files.
	P4::verify_job_user($job, \%record, P4::current_user());
	P4::verify_job_development_client($job, \%record, P4::current_client());
    } else {
	# Reviewer trying to print files.
	P4::verify_job_status($job, \%record, 'review', 'pass', 'fail');

	# Handle 'all files' expansion.
	my $i;
	for ($i = 0; $i <= $#ARGV; $i++) {
	    # Really means all the files
	    if ($ARGV[$i] eq '....') {
		$ARGV[$i] = '...';

	    # Means just the modified files
	    } elsif ($ARGV[$i] eq '...') {
		my %job_files;
		P4::old_opened_files($job, \%record, \%job_files);
		splice(@ARGV, $i, 1, keys(%job_files));
	    }
	}
    }

    # Prefix the work directory view to all specified files.
    my $user = $record{user};
    my $retry = $record{retry};
    $prefix = "//depot/$user/$job-$retry/";
}

# Add the prefix to all files.
my $i;
for ($i = 0; $i <= $#ARGV; ++$i) {
    # Special case - if the user specified just '#...' or '@...',
    # Assume it is meant to apply to all files.
    if ($ARGV[$i] =~ /^[#\@]/) {
	$ARGV[$i] = '...' . $ARGV[$i];
    }
    # Add the prefix to the file.
    $ARGV[$i] = $prefix . $ARGV[$i];
}

# Print all files. This produces output for the caller.
P4::print_files(@ARGV);

# Be nice.
1;