#!/usr/bin/env ruby

# Dropzone calls this first
# Loads an action script and calls the appropriate method

$runner_path = File.dirname(__FILE__)
$:.unshift($runner_path)
$:.unshift("bundled-gems")

# Disable output buffering
$stdout.sync = $stderr.sync = true

# Check runner is being called from within the lib directory
if Dir.pwd.split(File::SEPARATOR)[-1] != "lib"
  puts "Runner must be called from the within the lib directory"
  Process.exit
end

ruby_version = RbConfig::CONFIG["ruby_version"]

require "task_file_parser"
require "dropzone"
require "zip_files"
require "pastie_api"
require "Pashua"
include Pashua

if ARGV.length < 1
  puts "Requires task description file as argument"
  Process.exit
end

$dz = Dropzone.new

task_description_file = ARGV[0]

# Parse the task description file and set/export correct variables
t = TaskFileParser.new(task_description_file)

Process.exit unless t.parse

script = t.action
event = t.event
variables = t.variables
$items = t.items

variables.keys.each do |key|
  if key == "path"
    ENV['EXTRA_PATH'] = variables[key]
  end
  
  ENV[key] = variables[key]
end

require "filecopy"

password_variable = ENV['password_variable']

ENV[password_variable] = ENV[password_variable].unpack("m")[0] unless password_variable.nil?

extension = File.extname(script).downcase[1..-1]

require "bundler/setup-#{ruby_version}"

if (extension == "dropzone")
  load script
  method(event).call
elsif (extension == "dzbundle")
  Dir.chdir(script)
  $:.unshift(script)
  if File.exists?(script + "/" + "action.py")
    ENV["runner_path"] = $runner_path
    $items = [] if not $items
    exec(ENV["PYTHON_PATH"], $runner_path + "/" + "python_runner.py", event, *$items)
  else
    load script + "/" + "action.rb"
    method(event).call
  end
else
  puts "Action filename error"
end
