#!/usr/bin/env ruby
require "pathname" # Use Pathname to follow symlinks
require "rubygems"
gem "builder" #, "2.1.2"

gem 'activesupport'
gem 'activerecord'

require "active_support"
require 'active_record'
require "r18n-core"
require 'fileutils'

BUILDWISE_DIR = File.join(File.dirname(Pathname.new(__FILE__).realpath), '..')
BUILDWISE_LIB_DIR = File.join(BUILDWISE_DIR, 'lib')
$:.unshift BUILDWISE_LIB_DIR

RACK_ENV = ENV['RACK_ENV'] || "production"

require "buildwise/manager"
require "buildwise/utils"
require "buildwise/constants"

# puts "#{Time.now} [INFO] Build Runner on #{RACK_ENV}"
puts "\n\n==> #{Time.now} [Build] Start"

require 'erb'
db_yml_template = File.read "config/database.yml"
db_yml_content = ERB.new(db_yml_template).result(binding)

env_name = ARGV[0]
$build_id = ARGV[1]
$force = (ARGV[2] == "true")

puts "\n\n==> #{Time.now} [Build] load db: #{RACK_ENV}"
db_opts = YAML::load(db_yml_content)[RACK_ENV]
ActiveRecord::Base.establish_connection(db_opts)

def find_build

  Dir.glob("#{BUILDWISE_DIR}/app/models/*.rb").each { |file| require file }
  sleep 0.5 # wait a build to be persistented in the database
  if $force
    $the_build = Build.find_by_id($build_id)
  else
    $the_build = BuildQueue.find_by_id($build_id)
  end

  if $the_build.nil? 
    puts("[Warning] failed to find build |#{$build_id}| for env: #{RACK_ENV} : Last Build: #{Build.last.inspect}")
    sleep 1  # give it one more chance
    $the_build = Build.find_by_id($build_id)
    raise "The build is still not found!" if $the_build.nil?     
  end
  
    
  puts "#{Time.now} [INFO] buildwise-build.rb #{RACK_ENV} | finding a build |#{$build_id} => #{$the_build.project.name}| (#{$force})..."
  $application_name = $the_build.project.identifier if $the_build
end

# puts "[BENCHMARK] #{Time.now} Starting new build: #{$the_build}"
begin
  find_build
  $exit_code = 0
  if $application_name
    puts "#{Time.now} [INFO] Running build command: for '#{$application_name}', build: #{$build_id}"
    command = BuildWise::BuildCommand.new($application_name, cli_options = {:force => $force, :build => $the_build})
    $exit_code = command.run
  end
ensure
  puts "#{Time.now} [INFO] BuildCommand finished with exit code: #{$exit_code}"
  if $the_build && $the_build.finish_time.nil?
    $the_build.finish_time = Time.now
    $the_build.save
  end
  $exit_code  
end
