#!/usr/bin/env ruby

require "trollop"
require File.join(File.expand_path("..", File.dirname(__FILE__)),"lib","nailed")
require File.join(File.expand_path("..", File.dirname(__FILE__)),"db","database")

bugzilla_client = Nailed::Bugzilla.new
github_client = Nailed::Github.new

opts = Trollop::options do
  opt :migrate, "Set database to pristine state", :short => 'm'
  opt :upgrade, "Upgrade database", :short => 'u'
  opt :bugzilla, "Refresh bugzilla database records", :short => 'b'
  opt :github, "Refresh github database records", :short => 'g'
  opt :l3, "Refresh l3 trend database records", :short => 'l'
  opt :server, "Start a dashboard webinterface", :short => 's'
end

abort("try nailed -h") if opts.all?{|k,v| v.is_a?(FalseClass)}

if opts[:server_given]
  if Nailed::PRODUCTS["products"].nil?
    abort("Add some data, there is nothing to be shown")
  else
    begin
      `#{File.join(File.expand_path("..", File.dirname(__FILE__)),"bin","app")}`
    rescue Interrupt
      sleep 2
      exit
    end
  end
end

opts.each_pair do |key,val|
  case key
  when :migrate
    if val
      print("Are you sure? This will delete all data from the database. (y/n) ")
      if gets.strip == "y"
        Product.auto_migrate!
        Bugreport.auto_migrate!
        Bugtrend.auto_migrate!
        L3Trend.auto_migrate!
        Organization.auto_migrate!
        Repository.auto_migrate!
        Pullrequest.auto_migrate!
        Pulltrend.auto_migrate!
        Nailed.fill_db_after_migration(github_client.client)
        Nailed.log("info", "Database migrated")
        abort "Database migrated"
      else
        abort "Aborting..."
      end
    end
  when :upgrade
    if val
      print "Are you sure? This will create new tables, new columns, but not change anything existing. (y/n) "
      if gets.strip == "y"
        Product.auto_upgrade!
        Bugreport.auto_upgrade!
        Bugtrend.auto_upgrade!
        L3Trend.auto_upgrade!
        Organization.auto_upgrade!
        Repository.auto_upgrade!
        Pullrequest.auto_upgrade!
        Pulltrend.auto_upgrade!
        Nailed.fill_db_after_migration(github_client.client)
        Nailed.log("info", "Database upgraded")
        abort "Database upgraded"
      end
    end
  when :bugzilla
    if val
      bugzilla_client.get_bugs
      bugzilla_client.write_bug_trends
    end
  when :github
    if val
      github_client.update_pull_states
      github_client.get_open_pulls
    end
  when :l3
    if val
      bugzilla_client.write_l3_trends
    end
  end
end