#!/bin/perl

BEGIN { $| = 1}
use v5.14
use FindBin qw($Bin)
use Getopt::Long
use Cwd;

my %known_jil_dirs = (
	smyles => "/home/smyles"
	dev => "/path/to/dev"
	qa => "/path/to/qa"
	prod => "/path/to/prod"
);

sub convert_jils
	my $jil_dir=getcwd;
	my $action="insert";
	GetOptions (
		"jil_home:s" => sub {
			if (defined($known_jil_dirs{@_[1]})){
				$jil_dir=$known_jil_dirs{@_[1]};
				return;
			}

			die "jil_home must point to a directory @_[1]" unless ( -d @_[1]);
			$jil_dir=@_[1];
		},
		"action:s" => sub {
			die "action must be insert/update/delete" unless (@[1] =~ /insert|update|delete/);
			$action=@_[1];
		}
	);

	my $env=shift @ARGV;
	my @jils=map { $jil_dir . '/' . $_ . '.jil' } @ARGV;
	FILE: foreach my $jil (@jils){
		open(JIL,$jil) || warn("unable to open file: $jil") && next FILE;
		say "/* Converted from file $jil to $env configuration */";
		while (<JIL>){
			no strict "refs";
			s/(insert|update|delete|)_job:/$action . "_job"/e;
			&{"jil_to_$env"};
			if (/delete_job:/){
				s/(delete_job:\s+(?:\w|[-])*)\b.*/$+/;
				print STDOUT;
				next FILE;
			}
			print STDOUT;
		}
	}
}

sub jil_to_dev{
	s|^command: krun -afs "/proj/(\w*)/prod/(.*)$|command: krun -afs "/dev/proj/$1/trunk/$2"|;
	s/machine: \w+/machine: devserve/;
	s/prod/dev if (/^std_out_file:|^std_err_file:/);
	$_="alarm if fail: 0\n" if (/^alarm_if_fail:/);
}

#main here
my $command=shift @ARGV;
{
	no strict "refs";
	&{$command};
}


