require 'fileutils'

# Path vagrant to not delete pre-existing package file (pull request submitted upstream)

module Vagrant
  class Action
    module General
      
			class Package
				def recover(env)
          unless env["vagrant.error"].is_a?(Errors::PackageOutputExists)
						# Cleanup any packaged files if the packaging failed at some point.
						File.delete(tar_path) if File.exist?(tar_path)
					end
        end
			end

		end
	end
end

module VagrantAWS
	class Action
		class CreateImage
			include Vagrant::Util

			PACKAGE_VAGRANTFILE = <<EOT
Vagrant::Config.run do |config|
  # This Vagrantfile is auto-generated by `vagrant aws create_image` to contain
  # the image id and region. Custom configuration should be placed in
  # the actual `Vagrantfile` in this box.
  config.vm.base_mac = "000000000000"  # Unneeded
	config.aws.image = "<%= image %>"
	config.aws.region = "<%= region %>"
end
EOT

			attr_reader :temp_dir, :image

			def initialize(app, env)
				@app = app
				@env = env
			end

			def call(env)
				@env = env

				raise Vagrant::Errors::VMNotCreatedError if !@env["vm"].created?
				raise Vagrant::Errors::VMNotRunningError if !@env["vm"].vm.running?
				raise VagrantAWS::Errors::EBSDeviceRequired, :command => "box_create" if @env["image.register"] and @env["vm"].vm.root_device_type != "ebs"
			
				if @env["image.register"]
					@env.ui.info I18n.t("vagrant.plugins.aws.actions.create_image.creating")
					@image = @env["vm"].connection.create_image(@env["vm"].vm.id, @env['image.name'], @env['image.desc'])
					@image = @env["vm"].connection.images.new({ :id => @image.body['imageId'] })
					@image.wait_for { state == "available" }
				else
					@image = @env["vm"].connection.images.get(@env["vm"].vm.image_id)
				end

				setup_temp_dir
				export

				@app.call(@env)
				
				cleanup_temp_dir
			end

			def recover(env)
				if env["image.register"]
					env.ui.info I18n.t("vagrant.plugins.aws.actions.deregister_image.deregistering", :image => @image.id)
					@image.deregister(!@image.root_device_name.nil?)  # Don't try to delete backing snapshot if it was not created
				end
				cleanup_temp_dir
			end
		
			def cleanup_temp_dir
				if temp_dir && File.exist?(temp_dir)
					FileUtils.rm_rf(temp_dir)
				end
			end

			def setup_temp_dir
				@env.ui.info I18n.t("vagrant.actions.vm.export.create_dir")
				@temp_dir = @env["export.temp_dir"] = @env.env.tmp_path.join(Time.now.to_i.to_s)
				FileUtils.mkpath(@env["export.temp_dir"])
			end
		
			# Write a Vagrantfile with the relevant information
			def export
				File.open(File.join(@env["export.temp_dir"], 'Vagrantfile'), "w") do |f|
					f.write(TemplateRenderer.render_string(PACKAGE_VAGRANTFILE, {
						:image => @image.id,
						:region => @env["config"].aws.region
					}))
				end
				File.open(File.join(@env["export.temp_dir"], 'image.json'), "w") do |f|
					f.write(@image.to_json)
				end
			end


		end
	end
end

