#!/usr/bin/ruby

require 'rubygems'
require 'optparse'
require 'right_aws'

THIS_FILE = File.symlink?(__FILE__) ? File.readlink(__FILE__) : __FILE__
require File.expand_path(File.join(File.dirname(THIS_FILE), '..', 'lib', 's3_html_indexer'))

options = {}
opts = OptionParser.new
opts.on('-k', '--key KEY', "S3 key path (Ex: kvm/centos/5.6/RightImage_CentOS_5.6_x64_v5.7.14.qcow2.bz2)") { |key| options[:key] = key }
opts.on('-s', '--source BUCKET', "Source S3 bucket (Ex: rightscale-cloudstack-dev)") { |bucket| options[:bucket_from] = bucket }
opts.on('-d', '--destination BUCKET', "Destination S3 bucket (Ex: rightscale-cloudstack)") { |bucket| options[:bucket_to] = bucket }
opts.on_tail('-h', '--help', "Show this message") do
  puts "#{opts}\n"
  return false
end

begin
  opts.parse!
  mandatory = [:bucket_to, :bucket_from, :key]
  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

raise "ERROR: you must define AWS_ACCESS_KEY_ID in you environment. " unless ENV["AWS_ACCESS_KEY_ID"]
raise "ERROR: you must define AWS_SECRET_ACCESS_KEY in you environment. " unless ENV["AWS_SECRET_ACCESS_KEY"]

s3 = RightAws::S3.new(ENV["AWS_ACCESS_KEY_ID"], ENV["AWS_SECRET_ACCESS_KEY"])
bucket_from = s3.bucket(options[:bucket_from])
bucket_to = s3.bucket(options[:bucket_to])

puts "Moving file #{options[:key]} from #{options[:bucket_from]} to #{options[:bucket_to]}"
key_from = RightAws::S3::Key.create(bucket_from, options[:key])
key_to = RightAws::S3::Key.create(bucket_to, options[:key])
key_from.move(key_to)
raise "File move failed" unless key_to.exists?

puts "Granting public read"
grant = RightAws::S3::Grantee.new(key_to, 'http://acs.amazonaws.com/groups/global/AllUsers', 'READ', :apply_and_refresh)
raise "Grant update failed" unless grant

puts "Reindexing source bucket #{bucket_from}"
indexer_from = RightImageTools::S3HtmlIndexer.new(options[:bucket_from], ENV["AWS_ACCESS_KEY_ID"], ENV["AWS_SECRET_ACCESS_KEY"])
indexer_from.to_html("index-from.html")
indexer_from.upload_index("index-from.html")

puts "Reindexing destination bucket #{bucket_to}"
indexer_to = RightImageTools::S3HtmlIndexer.new(options[:bucket_to], ENV["AWS_ACCESS_KEY_ID"], ENV["AWS_SECRET_ACCESS_KEY"])
indexer_to.to_html("index-to.html")
indexer_to.upload_index("index-to.html")
