#!/usr/bin/env ruby

base_path = File.expand_path File.join(File.dirname(__FILE__), '..')
$:.unshift File.join(base_path, 'lib')

# TODO: Replace with bundle install --standalone (Bundler v1.1)
ENV['BUNDLE_GEMFILE'] ||= File.join(base_path, 'Gemfile')

require 'onetime'
require 'onetime/cli'
require 'rubygems'
require 'drydock'

# Command-line interface for bin/stella
class OT::CLI::Definition
  extend Drydock

  before do
    puts "" # separate our content from the bootstrapping banner
  end

  global :v, :verbose, 'Increase output' do
    @verbose ||= 0
    @verbose += 1
  end

  global :D, :debug do
    OT.debug = true
  end

  about 'Ruby irb with Onetime preloaded'
  command :console do
    cmd = format('irb -I%s -ronetime/console', File.join(OT::HOME, 'lib'))
    OT.ld cmd
    Kernel.exec cmd
  end

  usage 'ots version'
  command :version do
    puts format('Onetime %s', OT::VERSION.inspect)
  end
  alias_command :build, :version

  usage 'ots migrate MIGRATION_SCRIPT'
  about 'Run a migration script from the migrate/ directory'
  command migrate: OT::CLI

  usage 'ots move-keys SOURCEDB TARGETDB [filter]'
  command move_keys: OT::CLI

  usage 'ots customers'
  option :l, :list, "List customer domains (by count)"
  option :c, :check, "Show customer records where custid and email do not match (obscured)"
  command customers: OT::CLI

  usage 'ots domains'
  option :l, :list, "List domains"
  command domains: OT::CLI

  usage 'ots revalidate-domains'
  about 'Revalidate domain verification status. Optionally specify a domain and/or customer_id.'
  option :d, :domain, String, "Domain to revalidate"
  option :c, :custid, String, "Customer ID to revalidate"
  command revalidate_domains: OT::CLI
end

begin
  Drydock.run! ARGV, STDIN
rescue RuntimeError => e
  warn e.message
rescue StandardError => e
  puts e.message
  puts e.backtrace
  exit 1
end
