#!/usr/local/bin/perl -w

use strict;
use Cwd;
use File::Basename;
use Getopt::Std;
use DeployUtils::Logger;
use Clearcase::Cmd;
use DeployUtils::RmPkgInfo;
use DeployUtils::BuildFile;

use vars qw ( $opt_h $opt_d $opt_c $opt_p $opt_v $opt_V );

#==============================================================================
#   Usage
#==============================================================================
sub Usage
{
    my $msg = shift;

    my $useStr = 
"Usage:
$0 [-h] [-d N] [-p] [-v ver | -V | -l rtagId | -c \"comment\" ] files...
where:
    -h    : This help page
    -d N  : Sets Debugging level to N
    -p    : Executes a Press Enter to Continue on termination of script
    The following are mutually exclusive and only one may be supplied
    -v    : Use ver as the version number, overrides version number from build.pl
    -V    : Prompts for version number to override from build.pl
    -l    : Find latest work in progress version in Release rtag.
    -c    : Checkout all files with the this comment.
          : If Supplied will not use Release Manager to get comment details

This script will checkout all files supplied on the command line.  If -c not supplied
it will find the build.pl file for this tree and use it to get package details and then
get the comment from Release Manager for this package.  If -c is supplied it will use it.
";
    print "$msg \n" if ( defined($msg) );
    print $useStr;
    exit 0;
}   # Usage

getopts ('hd:pc:v:V');

Usage() if ( defined($opt_h) );

# dont want to make debug less than 3
setLogLevel($opt_d) if ( defined($opt_d));

my $buildInfo;
my $rmInfo;

if ( ! defined($opt_c) )
{
    my $buildDir = cwd();

    while ( $buildDir ne "" )
    {
        last if ( -f "$buildDir/build.pl" );
        $buildDir = dirname($buildDir);
    }

    if ( $buildDir ne "" )
    {
        $buildInfo = DeployUtils::BuildFile->new("$buildDir/build.pl");
        if ( !defined($opt_v) && defined($opt_V) )
        {
            LogNorm("-n", "Enter Version number for [" . $buildInfo->getBuildName() . "], (default use RM)...");         
            $opt_v = <STDIN>;
            chomp $opt_v;
            $opt_v = $buildInfo->getBuildVersion() if ( $opt_v eq "" );
        }
        elsif ( ! defined($opt_v) )
        {
            $opt_v = $buildInfo->getBuildVersion();
        }

        LogNorm("Retrieving package info form RM for [" . $buildInfo->getBuildName() . "], [$opt_v]...");
        $rmInfo = DeployUtils::RmPkgInfo->new({ PKG_NAME => $buildInfo->getBuildName(), PKG_VERSION =>  $opt_v});

        if ( $rmInfo->foundDetails() )
        {
            LogError("Package [" . $rmInfo->pkg_name() . "] Version [" . $rmInfo->pkg_version() . "] is locked") if ( $rmInfo->pv_dlocked() eq "Y" );
            $opt_c = $rmInfo->pv_reason();
            $opt_c =~ s/\r\n/\n/g;
            chomp $opt_c;
            LogError("RM Comment found is empty, please fix") if ( $opt_c eq "" );
            LogNorm("Setting Checkout Comment from RM to [$opt_c]");
        }
        else
        {
            LogError("Unable to get RM comment");
        }
    }
    else
    {
        LogError("Unable to find build.pl in the current tree");
    }
}

map { $_ = "\"$_\"" } @ARGV;

my $coCmd = Clearcase::Cmd->new();

$coCmd->abortOnError(0);
$coCmd->processOutput(0);
$coCmd->CCcmd("checkout");
$coCmd->CCargs("-reserved");
$coCmd->CCaddArgs("-comment \"$opt_c\"");
$coCmd->CCaddArgs(@ARGV);
LogNorm("Checking out all Files");
$coCmd->CCexecute();

# regardless of how or where this program end this will run (unless user Ctrl-C etc)
# so if -p supplied we put a wait for enter
END
{
    if ( $opt_p )
    {
        LogNorm("Press Enter To Continue");
        getc();
    }
}

# -------------------------------------------------------------------------
sub GetYesNoQuit
#
# -------------------------------------------------------------------------
{
    LogNorm("-n", "$_[0] (default: y) [y,n,q=quit]: ");

    while ( <STDIN> )
    {
        chomp;

        tr /A-Z/a-z/;
        
        return "y"  if ( /^$/ );
        return "$1" if ( /^ *([yn]{1})$/ );
        exit 1      if ( /^ *(q{1})/ );
        LogNorm("-n", "Please re-enter response? (default: y) [y,n,q]: ");
    }
}

