#!/usr/local/bin/perl -w

use strict;
use Getopt::Std;
use DeployUtils::Logger;
use Clearcase::LsCmd;
use Clearcase::Cmd;

use vars qw ( $opt_h $opt_d $opt_c $opt_p );

#==============================================================================
#   Usage
#==============================================================================
sub Usage
{
    my $msg = shift;

    my $useStr = 
"Usage:
$0 [-h] [-d N] [-p] [-c \"comment\"] dir
where:
    -h    : This help page
    -d N  : Sets Debugging level to N
    -p    : Executes a Press Enter to Continue on termination of script
    -c    : Checkout all files with the this comment.

This script runs an the Clearcase LsCmd to get a list of all Checked In File.
It then does a checkout of those files with the the comment if one is supplied
";
    print "$msg \n" if ( defined($msg) );
    print $useStr;
    exit 0;
}   # Usage

getopts ('hd:pc:');

Usage() if ( defined($opt_h) );

# dont want to make debug less than 3
setLogLevel($opt_d) if ( defined($opt_d));

my $dir = (defined($ARGV[0])) ? $ARGV[0] : ".";

my $CClist = Clearcase::LsCmd->new($dir);
LogNorm("Getting a list of Checked In Files in " . $CClist->CCcwd());

if ( $CClist->CCexecute() == 0 )
{
    if ( $CClist->getNumByState($Clearcase::LsCmd::StateCheckedIn) > 0 )
    {
        # get list of checked in files
        my $CiFiles = $CClist->getListByState($Clearcase::LsCmd::StateCheckedIn);
        map { $_ = "\"$_\"" } @$CiFiles;

        my $coCmd = Clearcase::Cmd->new();

        $coCmd->abortOnError(0);
        $coCmd->processOutput(0);
        $coCmd->CCcmd("checkout");
        $coCmd->CCargs("-reserved");
        if ( defined($opt_c))
        {
            $coCmd->CCaddArgs("-comment \"$opt_c\"");
        }
        else
        {
            $coCmd->CCaddArgs("-ncomment");
        }
        $coCmd->CCaddArgs(@$CiFiles);
        LogNorm("Checking out all Files");
        $coCmd->CCexecute();
    }
    else
    {
        LogNorm("No Checked In Files Found");
    }
}
else
{
    LogError("Failed to execute Ls Command");
}

# 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]: ");
    }
}

