#!/usr/bin/env ruby

require 'rubygems'
require 'optparse'
require 'sequel'

db_opts = {}
echo = nil
env = nil
logfile = nil
migrate_dir = nil
migrate_ver = nil
load_dir = nil

opts = OptionParser.new do |opts|
  opts.banner = "Sequel: The Database Toolkit for Ruby"
  opts.define_head "Usage: sequel <uri|path> [options]"
  opts.separator ""
  opts.separator "Examples:"
  opts.separator "  sequel sqlite://blog.db"
  opts.separator "  sequel postgres://localhost/my_blog"
  opts.separator "  sequel config/database.yml"
  opts.separator ""
  opts.separator "For more information see http://sequel.rubyforge.org"
  opts.separator ""
  opts.separator "Options:"

  opts.on_tail("-?", "--help", "Show this message") do
    puts opts
    exit
  end

  opts.on("-e", "--env ENV", "use environment config for database") do |v|
    env = v
  end
  
  opts.on("-E", "--echo", "echo SQL statements") do
    echo = true
  end
  
  opts.on("-l", "--log logfile", "log SQL statements to log file") do |v|
    logfile = v
  end
  
  opts.on("-L", "--load-dir DIR", "loads all *.rb from specifed directory") do |v|
    load_dir = v
  end
  
  opts.on("-m", "--migrate-directory DIR", "run the migrations in directory") do |v|
    migrate_dir = v
  end
  
  opts.on("-M", "--migrate-version VER", "migrate the database to version given") do |v|
    migrate_ver = Integer(v)
  end

  opts.on_tail("-v", "--version", "Show version") do
    puts "sequel #{Sequel.version}"
    exit
  end
end
opts.parse!

db = ARGV.shift

if db.blank?
  puts opts
  exit 1
end

if logfile || echo
  require 'logger'
  db_opts[:loggers] = []
  db_opts[:loggers] << Logger.new(logfile) if logfile
  db_opts[:loggers] << Logger.new($stdout) if echo
end

if File.exist?(db)
  require 'yaml'
  env ||= "development"
  db_config = YAML.load_file(db)
  db_config = db_config[env] || db_config[env.to_sym] || db_config
  db_config.each{|(k,v)| db_config[k.to_sym] = db_config.delete(k)}
  db_config.merge!(db_opts)
end

begin
  DB = Sequel.connect(*(db_config ? [db_config] : [db, db_opts]))
  DB.test_connection
  if migrate_dir
    Sequel::Migrator.apply(DB, migrate_dir, migrate_ver)
    exit
  end
rescue => e
  puts "#{e.class}: #{e.message}"
  puts e.backtrace.first
  exit 1
end

Dir["#{load_dir}/**/*.rb"].each{|f| load(f)} if load_dir

require 'irb'
puts "Your database is stored in DB..."
IRB.start
