#!/usr/bin/env ruby

$LOAD_PATH.unshift(File.dirname(File.realpath(__FILE__)) + '/../lib')
require 'pg_query'
require 'sqlint'

LIMIT = 1000

if ARGV.include?("--version")
  puts SQLint::VERSION
  exit 0
end

if ARGV.empty? || ARGV.include?("--help") || ARGV.include?("-h")
  puts "Usage: sqlint file.sql ..."
  exit 0
end

ERROR_TYPES = {error: "ERROR", warning: "WARNING"}

class String
  def sanitise
    gsub(/[[:cntrl:]+]/) do |bad|
      bad.codepoints.map { |c| "\\%04d" % c }.join
    end
  end
end

saw_errors = false
ARGV.each do |filename|
  File.open(filename, 'r') do |file|
    results = SQLint::Linter.new(filename, file).run.first(LIMIT)
    results.each do |lint|
      message_lines = lint.message.split("\n")
      puts [
        lint.filename,
        lint.line,
        lint.column,
        ERROR_TYPES[lint.type] + " " + message_lines.shift.sanitise
      ].join(":")
      message_lines.each do |line|
        puts "  " + line.sanitise
      end

      saw_errors ||= (lint.type == :error)
    end
  end
end

exit 1 if saw_errors
