#!/usr/bin/env ruby

LKP_SRC = ENV['LKP_SRC'] || File.dirname(File.dirname(File.realpath($PROGRAM_NAME)))

require "#{LKP_SRC}/lib/job2sh"
require "#{LKP_SRC}/lib/job"
require "#{LKP_SRC}/lib/log"
require 'optparse'
require 'ostruct'
require 'yaml'

$opt_file = STDOUT

opt_parser = OptionParser.new do |opts|
  opts.banner = "Usage: #{$PROGRAM_NAME} [options] job.yaml"

  opts.separator ''
  opts.separator 'options:'

  opts.on('-o FILE', '--output FILE', 'save shell script to FILE (default: stdout)') do |file|
    $opt_file = File.open(file, 'w', 0o775)
  end

  opts.on_tail('-h', '--help', 'Show this message') do
    puts opts
    exit
  end
end

argv = if ARGV == []
         ['-h']
       else
         ARGV
       end
opt_parser.parse!(argv)

def find_jobfile(jobfile)
  return jobfile if File.exist?(jobfile)

  search_paths = [Dir.pwd, File.join(LKP_SRC, 'jobs')]
  search_paths.each do |search_path|
    search_jobfile = File.join(search_path, jobfile)
    return search_jobfile if File.exist?(search_jobfile)
  end
  puts("Cannot find job #{jobfile} in directories:"); puts search_paths
  exit 1
end

begin
  job = Job2sh.new
  jobfile = find_jobfile(ARGV[0])
  job.load(jobfile)
  job.expand_params
rescue Job::ParamError => e
  log_error "Abandon job: #{e.message}"
  exit 1
end

$opt_file.puts job.to_shell
