#!/usr/local/bin/perl
# Integrate Wizard command line version
require "ctime.pl";
$date = &ctime(time);

use Getopt::Long;
$Getopt::Long::autoabbrev=0;	#make them specify exact option

unless(GetOptions("h",
		  "utm", "utb", "bname=s", "exec", "text=s")){
  die "Illegal Input Options, -h for help\n";
}


if($opt_h) {
  print "Integration Wizard Help\n-utm Update the Mainline (reverse integrate)
-utb Update the Branch   (forward integrate)
-exec execute the integrate
-text integration message for -utm
-bname <branch name>
-h this message \n";
  exit(1);
}



if((!$opt_utm || !$opt_utb) && !$opt_bname) {
  print "Usage: intwiz -h for help
Usage: intwiz {-utm|-utb}  -bname <branch name> -text <message for utm mode>\n";
  exit(1);
}



if($opt_utm && $opt_utb) {
  print "Hey, you can't do that\n";
  exit(1);
}

if($opt_utm && !$opt_text ) {
  if($opt_exec) {
    print "You need to specify a message  using -text <message>\n";
    exit(1);
  }
}

if($opt_utm) {
  $intdir="-r ";
}
else {
  $intdir="";
}


if($opt_exec) {
  $intoption="";
} else {
  $intoption=" -n";
}


if($opt_utb) {
  $btext="auto-int";
} else {
  $btext="auto-r-int ".$opt_text;
}

# Create a temporary client for fast integration
$intclient="intwiz_temp.$$";
$cmd="p4 client -o $intclient | p4 client -i > /dev/null";
system($cmd);
$cmd="p4 -c $intclient integ $intoption -v -i -d $intdir -b $opt_bname\n";
system($cmd);
  

if($intoption ne "-n") {
  
  $cmd="p4 -c $intclient change -o | sed 's/<.*>/$btext/' > /tmp/subout.$$";
  system($cmd);
  open(SUB, "</tmp/subout.$$") || die "Couldn't read change description\n";
  $submit=0;
  while(<SUB>) {
    
    if(/^Files/) {
      $submit++;
      close(SUB);
    }
  }
  if($submit) {
    # We should resolve first
    $cmd="p4 -c $intclient resolve -at";
    system($cmd);
      


    $cmd="p4 -c $intclient submit -i < /tmp/subout.$$";
    system($cmd);
  }
  system("p4 client -d $intclient > /dev/null");
}