#!/usr/bin/env ruby

require "optparse"
require_relative "../lib/commands/validate_schema"

def print_usage!
  $stderr.puts "Usage: validate-schema <schema> <data>, ..."
  $stderr.puts "       validate-schema -d <data>, ..."
end

command = Commands::ValidateSchema.new

parser = OptionParser.new { |opts|
  opts.on("-d", "--detect", "Detect schema from $schema") do
    command.detect = true

    # mix in common schemas for convenience
    command.extra_schemas += ["schema.json", "hyper-schema.json"].
      map { |f| File.expand_path(f, __FILE__ + "/../../schemas") }
  end
  opts.on("-s", "--schema SCHEMA", "Additional schema to use for references") do |s|
    command.extra_schemas << s
  end
  opts.on("-f", "--fail-fast", "Abort after encountering the first validation error") do |s|
    command.fail_fast = true
  end
}

if $0 == __FILE__
  parser.parse!
  success = command.run(ARGV.dup)

  if success
    command.messages.each { |m| $stdout.puts(m) }
  elsif !command.errors.empty?
    command.errors.each { |e| $stderr.puts(e) }
    exit(1)
  else
    print_usage!
    exit(1)
  end
end
