#!/usr/bin/ruby

require 'md_ruby_eval'

# this will only run if the script was the main, not load'd or require'd
to_require  = []
indentation = 40
line_length = 79
auto        = false
verbose     = false
dir         = Dir.pwd

OptionParser.new do |opts|
  opts.banner = File.read(__dir__ + '/../README.md') + "\n## Options:\n\n"

  opts.on('-d', '--directory DIR', 'Working directory') do |v|
    dir = File.expand_path v
  end

  opts.on('-r', '--require FILE', 'Require given files before processing the MD files') do |v|
    to_require << v
  end

  opts.on('-I', '--load-path PATH', 'Adds the path to LOAD_PATH') do |v|
    $LOAD_PATH << File.expand_path(v)
  end

  opts.on('-i', '--indent NUMBER', Integer, 'Default indentation of results') do |v|
    indentation = v
  end

  opts.on('-l', '--line NUMBER', Integer, 'Default maximum line length') do |v|
    line_length = v
  end

  opts.on('--[no-]auto',
          'Automatic mode. Finds `*.in.md` files outputting `*.out.md` files') do |v|
    auto = true
  end

  opts.on('--[no-]verbose',
          'Print code chunks right before their execution') do |v|
    verbose = true
  end
end.parse!

Dir.chdir dir do
  if auto
    input_paths = Dir.glob('*.in.{md,rb}')
    input_paths.each do |input_path|

      pid = fork do
        to_require.each { |p| require p }
        init_path = File.basename(input_path).gsub(/\.in\.(md|rb)/, '.init.rb')
        if File.exist? init_path
          puts "using: #{init_path}"
          load init_path
        end
        MDRubyEval.new input_path,
                       input_path.gsub(/(\.in)?\.(md|rb)$/) { ".out.#{$2}" },
                       binding,
                       indentation,
                       line_length,
                       verbose
      end

      Process.wait pid
    end
  else
    input_path, output_path = ARGV.map { |p| File.expand_path p }
    raise 'no input path' unless input_path && File.exist?(input_path)
    MDRubyEval.new input_path, output_path, binding, indentation, line_length, verbose
  end
end