#!/home/p/perl5 -w

use strict;
use FindBin qw($Bin);
use lib ("$Bin/../pm","$Bin/../lib","$Bin");

use Arguments;
use RiskMan;
use Benchmark;
use Time::HiRes;

use lib ("$TRISKMAN/share/site-perl");

use Tie::IxHash;
use Data::Dumper;
my $time = new Benchmark;

my %MAP = ( _AIDSQ => '$AUTO_INTRA_DSQUERY',
	    _ADSQ  => '$AUTO_DSQUERY',
	    _AHDSQ => '$AUTO_HIST_DSQUERY',
	    _AGDSQ => '$AUTO_GMR_DSQUERY',
	  );
my $dir = ".";
my $cmdpath   = "triskman/share/bin";
my $base_file = "";
my @cmd_s     = ();
my @con_s     = ();
my $cstr      = "";
my $noparent  = 0;
my $nopath    = 0;
my $ignore    = 0;
my $force     = 0;

my %tags = ();
tie %tags, 'Tie::IxHash';

%tags = ( insert_job    => "",
	  job_type      => 'b',
	  box_name      => "",
	  command       => "",
	  machine       => '`$AUTO_DA/tkautosys/share/bin/get_machine`',
	  permission    => "gx,mx,me",
	  std_out_file  => '>> $STDOUT',
	  std_err_file  => '>> $STDOUT',
	  alarm_if_fail => '0',
	  n_retrys      => "1",
	  profile       => '$AUTO_DA/tkautosys/env/auto.profile',
	  condition     => "",
	  box_success   => "",
	  start_times   => "",
	  start_mins    => "",
	  days_of_week  => "",
	  timezone      => "",
	  start_times   => "",
	  exclude_calendar => "",
	  date_conditions  => "",
          run_window       => "",
	  description      => "",
	  max_exit_success => "",
	  max_run_alarm    => "",
	);

my %ftags = map { ($_, undef) } keys %tags;

my %empty_keys = map { ($_, 1) } grep { !$tags{$_} } keys %tags;

my %xxx = (j => 1, b => 1, t => 1, c => 1, p => 1, f => 1);
my $mactype = undef;
my @switchs = map {
    my $x = $_; $x =~ s/_/ /g;
    my @chrs = $x =~ /(\b\w)/g;
    my $y = join "", @chrs;
    $x = $y;
    $x .= $xxx{$x} if exists $xxx{$x};
    $xxx{$y}++; ["$_|$x", \$tags{$_}, {USAGE => $_}];
} keys %tags;

my @switchs2 = map {
    my $x = $_; $x =~ s/_/ /g;
    my @chrs = $x =~ /(\b\w)/g;
    my $y = join "", @chrs;
    $x = $y;
    $x .= $xxx{$x} if exists $xxx{$x};
    $xxx{$y}++; ["force_$_|f_$x", \$ftags{$_}, {USAGE => "force $_"}];
} keys %tags;

my $parse = [["job|name|j"  => \$tags{insert_job}],
	     ["box|b"       => \$tags{box_name}],
	     ["type|t"      => \$tags{job_type}],
	     ["condition|c" => \$tags{condition}],
	     ["command|cmd" => \$tags{command}],
	     ["trys"        => \$tags{n_retrys}],
	     ["cpath|p"     => \$cmdpath],
	     ["base|f"      => \$base_file],
	     ["cs|cmd_s"    => \@cmd_s],
	     ["con_s"       => \@con_s],
	     ["nopath"      => \$nopath, {TYPE => argTypeSwitch}],
	     ["noparent|np" => \$noparent, {TYPE => argTypeSwitch}],
	     ["ignore"      => \$ignore, {TYPE =>argTypeSwitch}],
	     ["force"       => \$force, {TYPE =>argTypeSwitch}],
	     ["mac_type|mt" => \$mactype],
	     @switchs, @switchs2
	    ];

Arguments::parse(@ARGV, $parse, \&RiskMan::usage);

if ($tags{command} !~ /^\s*$/) {
    $tags{job_type} = "c"; # if command is force it to be command type
}

if ($mactype) {
    $tags{machine} =~ s/`$/ -jobtype $mactype`/;
}

if (my ($path, $name) = $tags{insert_job} =~ /(.*)\/(.*)/) {
    $tags{insert_job} = $name;
    unless ($nopath) {
	my ($path2, $name2) = $path =~ /(.*)\/(.*)/;
	$path = $path2 if ($name2 || "") eq $name;
	if ($base_file) {
	    my $pwd = `pwd`; chomp $pwd;
	    $base_file = "$pwd/$base_file" if $base_file !~ m|^/|;
	}
	chdir($path) or die "path doesn't exists! $path\n";
    }
}

if ($ignore && -e $tags{insert_job} && !$force) {
    print "IGNORING : $tags{insert_job}\n";
    exit 0;
} else {
    print -e $tags{insert_job} ? "UPDATING :" : "MAKING   :",
      " $tags{insert_job}\n";
}

elapsed();
# use base
if ($base_file) {
    open(BFILE, "$base_file") || die "can't open base file ($base_file)\n";
    my %base = map { my @x = (split /\s*:\s*/);
		     $x[0] =~ s/\s+//g;
		     $x[1] = join ":", @x[1..$#x];
		     $x[1] ||= "";
		     $x[1] =~ s/^\s+//;
		     chomp $x[1];
		     $x[1] =~ s/\s+$//;
		     @x[0,1]
		 } <BFILE>;
    close BFILE;
    while(my($key, $value) = each %base) {
	$value = "" unless defined $value;
	# always ignore
	next if $key =~ /insert_job|box_name/;
	# not always
	next if exists $empty_keys{$key} && $tags{$key};
	$tags{$key} = $value;
    }
}

elapsed();
my @path = split /\//, `pwd`;
if ($tags{job_type} eq 'b') {

    unless ($tags{insert_job}) {
	$tags{insert_job} = $path[$#path];
	$tags{box_name}   = $path[$#path - 1] unless $tags{box_name};
    } else {
	system "mkdir $tags{insert_job}"
	  unless -d $tags{insert_job};
	$dir = $tags{insert_job};
	$tags{box_name} = $path[$#path];
    }
} else {
    $tags{box_success} = ""; # only applicalbe on boxes
    unless ($tags{box_name}) {
	$tags{box_name} = $path[$#path];
	if ($tags{insert_job} =~ /\//) {
	    my @names = split /\//, $tags{insert_job};
	    if ($names[-2] eq '.') {
		$tags{insert_job} =~ s/^.\///;
	    } else {
		$tags{box_name} = $names[-2];
	    }
	}
    }
    unless ($tags{command}) {
	while(my($key, $value) = each %MAP) {
	    printf "%-10s => %-s\n", $key, $value;
	}
    }
    read_tag("command");
    while(my($key, $value) = each %MAP) {
	$tags{command} =~ s/$key/$value/g;
    };

    unless ($tags{command} =~ /\$AUTOAW/) {
	$tags{command} = '$AUTO_DA/' . "$cmdpath/$tags{command}"
	  unless $tags{command} =~ /^[\/\$]/;
	$tags{command} = '$AUTOAW "' . $tags{command} . '"'
	  unless $tags{command} =~ /\$AUTOAW/;
    }

#     $tags{command} = '$AUTO_DA/' . "$cmdpath/$tags{command}"
#       unless $tags{command} =~ /^\//;
#     $tags{command} = '$AUTOAW "' . $tags{command} . '"'
#       unless $tags{command} =~ /\$AUTOAW/;

#     $tags{command} = '$AUTOAW "$AUTO_DA/' . "$cmdpath/$tags{command}\""
# #      unless $tags{command} =~ /^\$AUTOAW/;
# #      unless $tags{command} =~ /\//;
#       unless $tags{command} =~ /\$AUTOAW/;
}

elapsed();

substitute(\%tags, "command", @cmd_s);
substitute(\%tags, "condition", @con_s);

chomp $tags{insert_job};
chomp $tags{box_name};

die "must specify job name\n" unless $tags{insert_job};

open(FILE, ">$dir/$tags{insert_job}") || die "can't create job $tags{insert_job}\n";

elapsed();

while(my($key, $value) = each %ftags) {
    next unless defined $value;
    $tags{$key} = $value;
}

while(my($key, $value) = each %tags) {
    $value =~ s/^\s+$//;
    next if $value eq '-' || $value eq "";
    next if $tags{job_type} eq 'b'
      && $key =~ /command|machine|std_out_file|std_err_file|n_retrys|profile/;
    next if $key eq 'box_name' && $noparent;
    if ($key =~ /command/) {
	my $val2 = $value;
	$val2 =~ s/^.*?\"//; $val2 =~ s/\"$//;
	foreach my $valx (values %MAP) {
	    $valx =~ s/\$/\\\$/;
	    $val2 =~ s/ $valx / DADBN /;
	}
	my $cmdlen = length($val2);
	warn "WARNING ***** : command length ($cmdlen)" if $cmdlen > 256;
    }
#    $value = "`$value`"
#      if ($key eq 'machine' && $value !~ /`.*`/);

    $value =~ s/.*\///
      if ($key eq 'insert_job');

    print FILE "$key: $value\n";
}

elapsed();
close FILE;
elapsed();

exit 0;

sub read_tag {
    my ($tag) = @_;
    while (!$tags{$tag}) {
	print "enter ($tag) : ";
	$tags{$tag} = <STDIN>;
    }
}

sub substitute {
    my ($hash, $tag, @ptrs) = @_;
    foreach my $str (@ptrs) {
	eval "\$hash->{$tag} =~ $str";
	die "ERROR in substitution $tag ($str): $@\n" if $@;
    }
}

sub elapsed {
#    my $time1 = new Benchmark;
#    print "time : ", timestr(timediff($time1, $time)), "\n";
#    $time = $time1;
}
