require ‘projectdx_pipeline/file’ require ‘projectdx_pipeline/database_configuration_template’ namespace :pipeline do

desc "Run commit stage build and tests"
task :commit => 'commit:default' do
  puts "You probably want this to run the pipeline:commit:configure, pipeline:commit:build,"
  puts "and pipeline:commit:test tasks, however..."
  puts "NOTE: You can't run the db:migrate task in the same command as your tests on Rails projects"
end

namespace :commit do
  task :configure
  task :build
  task :test

  namespace :configure do
    desc 'Setup database.yml for stage'
    task :database do
      dct = ProjectdxPipeline::DatabaseConfigurationTemplate.new('config/database.pipeline.yml')
      dct.render_to_file('config/database.yml')
    end

    desc 'Setup cms_config.yml for stage'
    task :cms do
      ProjectdxPipeline::File.copy('config/cms_config.deploy.yml', 'config/cms_config.yml')
    end
  end

  namespace :build do
    desc 'Clone reference database'
    task :clone_reference_database  do
      require 'pg'
      config = YAML.load_file('config/database.yml')['development']
      pg = PGconn.new(:host => config['host'], :port => config['port'],
                      :user => config['username'], :password => config['password'],
                      :dbname => 'postgres')

      db_name = config['database']
      db_ref = config['reference_db']
      pg.exec "SELECT killusers('#{db_ref}', '#{config['database']}')"
      pg.exec "DROP DATABASE IF EXISTS \"#{db_name}\""
      pg.exec "CREATE DATABASE \"#{db_name}\" TEMPLATE \"#{db_ref}\""
      pg.close
    end
  end
end

end