#!/usr/bin/env rake

require 'mixlib/shellout'
require 'rainbow/ext/string'

AUTH_KEY = ENV['DEIS_TEST_KEY'] || '~/.ssh/deis'
SSH_KEY = ENV['DEIS_TEST_SSH_KEY'] || '~/.vagrant.d/insecure_private_key'
HOSTS = ENV['DEIS_TEST_HOSTS'] || '172.17.8.100'
HOSTNAME = ENV['DEIS_TEST_HOSTNAME'] || 'local.deisapp.com'
EXAMPLE_APP = ENV['DEIS_TEST_APP'] || 'example-ruby-sinatra'

namespace :setup do
  task :all => ['create_ssh_key','clone_example_app']
  task :create_ssh_key do
    run_command("if [ ! -f #{AUTH_KEY} ]; then ssh-keygen -q -t rsa -f #{AUTH_KEY} -N '' -C deis && ssh-add #{AUTH_KEY} ; fi")
  end
  task :clone_example_app do
    run_command("if [ ! -d ./#{EXAMPLE_APP} ]; then git clone https://github.com/deis/#{EXAMPLE_APP}.git ; fi")
  end
end

namespace :tests do
  task :all => ['register','login','add_key','create_cluster','create_app','push_app','scale_app','verify_app']
  task :register do
    run_command("deis register http://deis.#{HOSTNAME} --username=test --email=test@test.co.nz --password=asdf1234 || true")
  end
  task :login do
    run_command("deis login http://deis.#{HOSTNAME} --username=test --password=asdf1234")
  end
  task :add_key do
    run_command("deis keys:add #{AUTH_KEY}.pub")
  end
  task :create_cluster do
    run_command("deis init dev #{HOSTNAME} --hosts=#{HOSTS} --auth=#{SSH_KEY}")
  end
  task :create_app do
    Dir.chdir(EXAMPLE_APP) do
      sleep 6  # give builder git time to wake up
      run_command('deis apps:create testing')
    end
  end
  task :push_app do
    Dir.chdir(EXAMPLE_APP) do
      run_command('git push deis master')
    end
  end
  task :scale_app do
    Dir.chdir(EXAMPLE_APP) do
      run_command('deis scale web=2')
    end
  end
  task :verify_app do
    run_command("curl -s http://testing.#{HOSTNAME} | grep -q 'Powered by Deis'")
  end
end

namespace :cleanup do
  task :all => ['destroy_app','destroy_cluster','remove_key','logout']
  task :destroy_app do
    Dir.chdir(EXAMPLE_APP) do
      run_command('deis apps:destroy --app=testing --confirm=testing')
    end
  end
  task :destroy_cluster do
    run_command("deis clusters:destroy dev --confirm=dev")
  end
  task :remove_key do
    run_command("deis keys:remove deis")
  end
  task :logout do
    run_command("deis auth:logout")
  end
end

def run_command(cmd)
  print "Running #{cmd}... ".color(:yellow)
  cmd = Mixlib::ShellOut.new(cmd).run_command
  if not cmd.error?
    puts "Success!".color(:green)
  else
    puts "Failed!".color(:red)
    puts cmd.stdout.color(:red)
    puts cmd.stderr.color(:red)
    raise "Command failed - stopping"
  end
end

task :default => ['setup:all', 'tests:all', 'cleanup:all']
