#!/usr/bin/ruby

require 'rubygems'
require 'rest_connection'
require 'trollop'
require 'highline/import'

options = Trollop::options do
  opt :from, "Copy MCIs from this Server Template (id)", :type => :integer, :required => :true
  opt :to, "Copy MCIs to this Server Template (id)", :type => :integer, :required => :true
  opt :skip, "Skip MCIs matching a certain regex", :type => :string
  opt :nice, "Non-Destructive update of the destination Server Template"
end

class MciCp
  def self.go(options)
    temp1 = ServerTemplate.find(options[:from])
    temp2 = ServerTemplate.find(options[:to])
    from_st = ServerTemplateInternal.new(:href => temp1.href)
    mci_payload = from_st.multi_cloud_images
    to_st = ServerTemplateInternal.new(:href => temp2.href)
    to_delete = to_st.multi_cloud_images
    mci_payload.each do |mci|
      begin
        if options[:skip] and mci['name'] =~ /#{options[:skip]}/
          puts "skipping #{mci['name']}, matches skip criteria" 
        else
          to_st.add_multi_cloud_image(mci['href'])
          puts "adding #{mci['name']}"
        end
      rescue => e
        puts "image #{mci['name']} already added, skipping" if ENV['DEBUG']
        to_delete.delete(mci)
      end
    end
    default_mci = mci_payload.find {|d| d['name'] =~ /CentOS.+x64/ and d['name'] !~ /EBS/}
    unless default_mci
      default_mci = mci_payload.first
    end
    puts "setting default mci #{default_mci['name']}"
    to_st.set_default_multi_cloud_image(default_mci['href'])
    unless options[:nice]
      to_delete.each do |mci|
        to_st.delete_multi_cloud_image(mci['href'])
        puts "deleting #{mci['name']}"
      end
    end
    puts 'done.'
  end
end

MciCp.go(options)