#!/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)

begin
  job = Job2sh.new
  jobfile = Job.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