module Mccloud::Provider
  module Aws
    module VmCommand

      def package(options=nil)

        #f=Fog::Compute.new({ :region => "eu-west-1", :provider => "AWS"})
        # i=f.create_image("i-c1ac2bb7","name","description")
        # f.images.all({ "Owner" => "self"})
        # f.deregister_image("ami-796d5b0d")

        time=Time.new
        strtime=time.strftime("%Y-%m-%d-%H-%M-%S")
        name=""

        if options["name"].nil?
          name="#{@name}-#{strtime}"
        else
          name=options["name"]
        end

        description=""
        if options["description"].nil?
          description="Autogenerated snapshot from machine #{@name}"
        else
          description=options["description"]
        end

        begin
          puts raw.id
          result=@provider.raw.create_image(raw.id,name,description)
          imageId=result.body["imageId"]
          env.ui.info "[#{@name}] image #{imageId} with #{description} being created"
          unless options["dontwait"]
            sleep 3
            counter=0
            max_tries=5
            #Pending
            state="pending"
            until state!="pending" do
              print "."
              sleep 2
              image=@provider.raw.images.get(imageId)

              if image.nil?
                sleep 3
                print "."
              else
                state=image.state
              end
            end
            env.ui.info ""
            env.ui.info "[#{@name}] creation done!"
          end
        rescue Fog::Service::Error => fogerror
          env.ui.error "[Error] #{fogerror}"

        end
      end

    end #module
  end #module
end #module
