#!/usr/bin/env ruby

require 'json'
require 'rest-client'

sleep(10) # sleeping ten seconds so first execution has a target.

# Pull Temporary Secret Key from Task Profile Role
unless ENV.include?('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI')
  puts 'Not running in ECS, this script serves no purpose.'
  exit
end

credentials = JSON.parse(RestClient.get "http://169.254.170.2#{ENV['AWS_CONTAINER_CREDENTIALS_RELATIVE_URI']}")

headers = {
  'X-Access-Key': credentials['AccessKeyId'],
  'X-Secret-Key': credentials['SecretAccessKey'],
  'X-Session-Token': credentials['Token']
}

headers = headers.collect { |k, v| "-H '#{k}: #{v}'" }.join(' ')
status = `curl -s -w "%{http_code}" -o /dev/null -XSETTINGS #{headers} http://127.0.0.1:8080`

puts "Attempted to update access keys; received a #{status} response."
