require 'serverspec'
require 'pathname'
require 'net/ssh'
require 'net/http'
require 'json'
require 'pp'

include Serverspec::Helper::DetectOS
include Serverspec::Helper::Ssh

# Ctrl + C
Signal.trap(:INT){
  |q| q.echo = true
  puts "SIGINT"
}

def port_of_latest_container
   uri = URI.parse "http://192.168.50.2:4243/containers/json"
   (JSON.parse Net::HTTP.get uri)[0]["Ports"].find {|e| e['PrivatePort'] == 22} ['PublicPort']
end

def vagrant_ssh_config
  opts = {}
  config = `vagrant ssh-config`
  config.each_line do |line|
    if match = /IdentityFile (.*)/.match(line)
      opts[:keys] =  [match[1].gsub(/"/,'')]
    elsif match = /Port (.*)/.match(line)
      opts[:port] = match[1]
    end
  end
  opts
end

case ENV['TEST_ENV']
when "docker"
  RSpec.configure do |c|
    c.before :all do
      host = "192.168.50.2"
      user = "vagrant"
      opts = {}
      opts[:keys] = ["./modules/docker/files/sshd/.ssh/id_rsa"]
      opts[:port] = (ENV['SSH_PORT'] || port_of_latest_container || 22).to_i
      opts[:user_known_hosts_file] = "/dev/null"
      c.ssh.close if c.ssh
      c.ssh = Net::SSH.start(host, user, opts)
    end
  end
when "vagrant"
  RSpec.configure do |c|
    opts = vagrant_ssh_config
    c.before :all do
      host = "127.0.0.1"
      user = "vagrant"
      opts[:user_known_hosts_file] = "/dev/null"
      c.ssh.close if c.ssh
      c.ssh = Net::SSH.start(host, user, opts)
    end
  end
else
  RSpec.configure do |c|
    if ENV['ASK_SUDO_PASSWORD']
      require 'highline/import'
      c.sudo_password = ask("Enter sudo password: ") { |q| q.echo = false }
    else
      c.sudo_password = ENV['SUDO_PASSWORD']
    end
    c.before :all do
      host = ENV['SSH_HOST']
      user = (ENV['SSH_USER'] || Etc.getlogin)
      opts = {}
      opts[:password] = c.sudo_password
      opts[:keys] = (ENV['SSH_KEY'] || [])
      opts[:port] = (ENV['SSH_PORT'] || 22).to_i
      opts[:user_known_hosts_file] = "/dev/null"
      c.ssh.close if c.ssh
      c.ssh = Net::SSH.start(host, user, opts)
    end
  end
end
