#!/usr/bin/ruby

require 'rubygems'
require 'optparse'
require 'ruby-debug'
require 'rest_connection'
require 'tmpdir'

require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'mci'))

def aws_id_from_href(href)
  id = href.split("/").last
  id.split("?").first
end

def ask(prompt)
  puts prompt+" "
  res = gets
  unless res =~ /^[yY]/
    puts "Aborting"
    exit 0
  end
end

def parse_options
  opts = OptionParser.new
  options = {}
  opts.on('-s', '--source MCI_SUFFIX', "Suffix of MCI to copy from i.e. 'v5.8.0_Beta_Dev2'") { |name| options[:src] = name}
  opts.on('-d', '--destination MCI_SUFFIX', "Suffix of MCI to copy to i.e. 'v5.8'") { |name| options[:dest] = name}
  opts.on_tail('-h', '--help', "Show help") do
    puts "#{opts}\n"
    return false
  end

  begin
    opts.parse!
    mandatory = [:src, :dest]
    missing = mandatory.select { |param| options[param].nil? }
    if not missing.empty?
      puts "Missing options: #{missing.join(", ")}"
      puts opts
      exit
    end
  rescue OptionParser::InvalidOption, OptionParser::MissingArgument
    puts $!.to_s
    puts opts
    exit
  end
  options
end

options = parse_options
ENV['REST_CONNECTION_LOG'] = Dir.tmpdir + "/mci_merge_rest.log"

mcis = MultiCloudImage.find_all
sources = []
dests   = []

mcis.each do |mci|
  if mci.name =~ /RightImage.*#{Regexp.escape(options[:src])}(_EBS)?$/
    sources << MultiCloudImageInternal.find(mci.rs_id.to_i)
  end
end

if sources.length == 0
  puts "Did not find any MCIs with suffix #{options[:src]} to copy"
  exit 0
end

puts "Found #{sources.length} MCIs to move: "

sources.each_with_index do |mci, i|
  # print out source mci
  print (i+1).to_s.ljust(2)+") "
  puts mci.name
  clouds = mci.multi_cloud_image_cloud_settings.map {|s| s.cloud}
  puts "    CLOUDS: "+clouds.join(", ")
  print "    -->"

  # find a destination mci and print that if found
  # else note we'll make a new mci for the destination
  name_no_suffix = mci.name.sub(options[:src],"").sub("_EBS","")
  dest_mci_name = name_no_suffix + options[:dest]
  dest_mci_name += "_EBS" if mci.name =~ /_EBS/ and dest_mci_name !~ /_EBS/
  found = mcis.find { |new_mci| new_mci.name == dest_mci_name }
  if found
    dest_mci = MultiCloudImageInternal.find(found.rs_id.to_i)
    dests << dest_mci
    print dest_mci.name
  else
    dests << dest_mci_name
    print "NEW MCI: "
    print dest_mci_name
  end
  puts ""
end

ask("Continue - Y/N?")

mci_tool = RightImageTools::MCI.new
sources.each_with_index do |src_mci, i|
  dest_mci = dests[i]
  if dest_mci.class == String
    src_mci.multi_cloud_image_cloud_settings.each do |s|
      image_id = aws_id_from_href(s.image_href)
      puts "New MCI with image: cloud_id=#{s.cloud_id.to_i}, mci_name=#{dest_mci}, image_id=#{image_id}"
      mci_tool.add_image_to_mci(
        :cloud_id=>s.cloud_id.to_i,
        :name=>dest_mci,
        :image_id=>image_id)
    end
  else
    src_mci.multi_cloud_image_cloud_settings.each do |s|
      image_id = aws_id_from_href(s.image_href)
      puts "Adding image to MCI #{dest_mci.rs_id}: cloud_id=#{s.cloud_id.to_i}, mci_id=#{dest_mci.rs_id}, image_id=#{image_id}"
      mci_tool.add_image_to_mci(
        :cloud_id=>s.cloud_id.to_i,
        :mci_id=>dest_mci.rs_id,
        :image_id=>image_id)
    end
  end
end

