#!/usr/bin/ruby.ruby4.0 

USAGE = %{
rescue (pry-rescue wrapper)

Usage:
  rescue [-i] <script.rb> [arguments...]

What it does:
  Runs <script.rb>, and if an uncaught exception is raised,
  pry will come to the rescue, giving you a pry prompt in the
  context where the exception was raised.

  You can then poke around to figure out why your code broke!

  If -i is specified, then rescue will open a REPL whether or
  not there was an exception. Specifying -i will also wrap
  Kernel.at_exit and run exit callbacks before launching the
  REPL if the script succeeds. This is useful for minitest and
  other testing frameworks.

  See the README (http://bitly.com/pry-rescue) for more.
}

ensure_repl = false

case ARGV[0]
when '-h', '--help'
  puts USAGE
  exit
when '-i'
  ensure_repl = true
  ARGV.shift
when /\A-/
  puts USAGE
  exit
else
  case File.basename(ARGV[0] || "")
  when 'rails'
    ENV['PRY_RESCUE_RAILS'] = 'true'
    exec(*ARGV)
  when 'rake'
    require File.realpath(File.expand_path('../../lib/pry-rescue.rb', __FILE__))
    PryRescue.load_rake ARGV[1]
    exit
  when /^re?spec$/
    ENV['SPEC_OPTS'] = "#{ENV['SPEC_OPTS']} -r pry-rescue/rspec"
    exec(*ARGV)
  end
end

if script = ARGV.shift
  $0 = File.expand_path(script)

  if File.exist? script
    require File.realpath(File.expand_path('../../lib/pry-rescue.rb', __FILE__))
    PryRescue.load $0, ensure_repl
  else
    $stderr.puts "Error: #{script.inspect} not found."
  end
else
  puts USAGE
end
