#!/usr/bin/env ruby
require 'rubygems'
require 'yaml'
require 'forgery'
require 'dictionaries'
require 'file_reader'
require 'optparse'

IDREGEX = /i-[0-9a-f]{8}/

EC2_SSH_KEY_NAME = ENV['EC2_KEYPAIR_NAME'] || 'default'
EC2_SSH_KEY_PATH = ENV['EC2_KEYPAIR_PATH'] || '~/.ec2/default-key-pair.pem'

#AMI_ID = "ami-5647a33f" # Amazon Base Fedora 8
#AMI_ID = "ami-c8ac48a1" # RightImage CentOS 5 Base
#AMI_ID = "ami-d510f1bc" # Within3 App Image
#AMI_ID = "ami-155cba7c"  # RightImage CentOS 5.2 Base
#AMI_ID = "ami-4f1dfc26" # Within3 App Base Image
#AMI_ID = "ami-af6283c6" # Within3 App Base Image
AMI_ID = "ami-3f688956" # Within3 App Base Image

Instance = Struct.new(:line, :instance_id, :image, :status, :url, :name)

def main
  case ARGV[0]
  when /spinup/
    options = {}
    opts = OptionParser.new
    opts.on('-n', '--name NAME') { |name| options[:name] = name }
    opts.on('-s', '--size SIZE') { |size| options[:instance_size] = size }
    opts.on('-f', '--user-data-file PATH') { |path| options[:user_data_file] = path }
    opts.on('-a', '--ami-id AMI_ID') { |ami_id| options[:ami_id] = ami_id }
    opts.on('-z', '--zone ZONE') { |zone| options[:zone] = zone }
    opts.parse!(ARGV)
    options[:name] ||= get_name_for_instance
    options[:ami_id] ||= AMI_ID
    options[:instance_size] ||= 'm1.large'
    options[:zone] ||= 'us-east-1c'
    puts "Spining up image with options: #{options.inspect}"
    spinup(options)
  when /spindown/
    raise "Need an instance name" unless ARGV[1]
    spindown ARGV[1]
  when /status/
    puts "Getting the status"
    instances = if ARGV[1] then [get_instance(ARGV[1])].compact else get_instances end
    instances.each do |instance|
      puts "%s\t%s\t%s\t%s" % [instance.name, instance.instance_id, instance.status, instance.url]
    end
  when /ssh/
    raise "Need an instance name" unless ARGV[1]
    instance = get_instance(ARGV[1])
    raise "Unknown instance name #{ARGV[1]}" unless instance
    ssh instance.url
  when /scp_up/
    raise "Need an istance name" unless ARGV[1]
    raise "Need a source path" unless ARGV[2]
    raise "Need a destination path" unless ARGV[3]
    instance = get_instance(ARGV[1])
    scp_up instance, ARGV[2], ARGV[3]
  when /webopen/
    raise "Need an instance name" unless ARGV[1]
    instance = get_instance(ARGV[1])
    raise "Unknown instance name #{ARGV[1]}" unless instance
    `open http://#{instance.url}`
  when /output/
    raise "Need an instance name" unless ARGV[1]
    console_output get_instance(ARGV[1])
  when /address/
    raise "Need an instance name" unless ARGV[1]
    instance = get_instance(ARGV[1])
    puts instance.url
  else
    puts "Fail."
  end
end


def run_instance(options={})
  instance_size = options.delete(:instance_size)
  image_id = options.delete(:ami_id)
  name = options.delete(:name)
  zone = options.delete(:zone)
  user_data_file = options.delete(:user_data_file)
  instance_options = "-t #{instance_size}"
  instance_options += " -f #{user_data_file}" if user_data_file
  instance_options += " -z #{zone}" if zone
  instance = parse_aws_status_line_into_instance `ec2-run-instances #{image_id} -k #{EC2_SSH_KEY_NAME} #{instance_options}`.split("\n")[-1], name
  write_instance_to_datastore(instance)
  instance
end

def get_name_for_instance
  Dictionaries.new[:company_names].random.downcase
end

def parse_aws_status_line_into_instance line, name=nil
  columns = line.split("\t")
  instance = Instance.new line, columns[1], columns[2], columns[5], columns[3], name
end

def get_instance(name)
  instances = load_instances_from_datastore
  instance_id = instances[name]
  `ec2-describe-instances #{instance_id}`.split("\n").select{ |l| l =~ /^INSTANCE/ }.inject([]) do |result, line|
    instance = parse_aws_status_line_into_instance(line, name)

    if instance.status != 'terminated'
      instance.name = name
      result << instance
    else
      result
    end
  end.compact.first
end

def get_instances
  instance_mappings = load_instances_from_datastore
  `ec2-describe-instances`.split("\n").select{|l| l =~ /^INSTANCE/}.inject([]) do |result, line|
    instance = parse_aws_status_line_into_instance(line)

    if instance.status != "terminated"
      instance.name = instance_mappings.find_name_by_instance_id(instance.instance_id)
      result << instance
    else
      result
    end
  end
end

def terminate_instances *instances
  `ec2-terminate-instances #{instances.map{|i| i.instance_id}.join(' ')}`
end

def ssh url
  puts url
  exec "ssh -i #{EC2_SSH_KEY_PATH} root@#{url}"
end

def scp_up instance, source, destination
  exec "scp -i #{EC2_SSH_KEY_PATH} #{source} root@#{instance.url}:#{destination}"
end

def console_output instance
  exec "ec2-get-console-output #{instance.instance_id}"
end

def spinup(options={})
  puts "Spinning up image"
  name = options[:name]
  current_instance = instance = run_instance(options)
  puts "Instance #{instance.instance_id} spinning up"

  still_loading = true
  while still_loading
    puts "waiting...#{current_instance.line}"
    sleep 2
    current_instance = get_instance(name)
    still_loading = current_instance.status == "pending"
  end

  puts "Instance running!"
  puts "name: #{current_instance.name}, id: #{current_instance.instance_id}, url: #{current_instance.url}"
end

INSTANCE_MAPPINGS_FILENAME = File.expand_path("~/.ec2/instance_mappings.yml")
def write_instance_to_datastore(instance)
  instances = load_instances_from_datastore || {}
  instances.merge!({instance.name => instance.instance_id})
  write_instances_to_datastore(instances)
end

def write_instances_to_datastore(instances)
  File.open(INSTANCE_MAPPINGS_FILENAME, "w+") do |f|
    f << instances.to_yaml
  end
end

def load_instances_from_datastore
  data = File.read(INSTANCE_MAPPINGS_FILENAME)
  instances = YAML.load(data)

  class << instances
    def find_name_by_instance_id(instance_id)
      select { |k,v| v == instance_id }[0]
    end
  end

  instances
end

def delete_instance_from_datastore(name)
  instances = load_instances_from_datastore
  instances.delete(name)
  write_instances_to_datastore(instances)
end

def spindown name
  puts "Spinning down #{name}"
  instance = get_instance(name)
  raise "Unknown instance name #{name}" unless instance

  terminate_instances instance

  while instance
    puts "waiting...#{instance.line}"
    sleep 2
    instance = get_instance(name)
  end

  delete_instance_from_datastore(name)

  puts "Terminated #{name}"
end

main
