chef_gem 'aws-sdk'
require 'aws-sdk'

node[:deploy].each do |application, deploy|
  if deploy[:application_type] != 'rails'
    Chef::Log.debug("Skipping s3_asset_manifest application #{application} " +
                    "as it is not an Rails app")
    next
  end
  s3_config = node[:s3_asset_manifest]
  puts "Bucket: #{s3_config["bucket"]}"

  AWS.config(
    access_key_id:     s3_config["access_key_id"],
    secret_access_key: s3_config["secret_access_key"],
    region:            s3_config['region']
  )

  s3 = AWS::S3.new
  bucket = s3.buckets[s3_config['bucket']]
  manifests = bucket.objects.with_prefix('assets/manifest-').to_a
  filepath = manifests.sort_by(&:last_modified).last.key

  public_dir = "#{node[:deploy][application][:deploy_to]}/current/public"

  directory "#{public_dir}/assets" do
    owner deploy[:user]
    group deploy[:group]
    mode 0744
    action :create
  end

  remote_file File.join(public_dir, filepath) do
    source "https://s3.amazonaws.com/#{s3_config['bucket']}/#{filepath}"
    owner deploy[:user]
    group deploy[:group]
    mode 0644
  end

end
