if node['ec2'].nil?
  Chef::Log.warn('Refusing to install CloudWatch Logs because this does not appear to be an EC2 instance.')
  return
end

install_directory = node['cwlogs']['install']['directory']
local_script = "#{install_directory}/#{node['cwlogs']['install']['script']['name']}"

if node['cwlogs']['accepted_regions'].include? node['cwlogs']['region']
  region = node['cwlogs']['region']
else
  Chef::Log.info("Cloudwatch, #{node['cwlogs']['region']} is not a valid region for Cloudwatch")
  region = node['cwlogs']['accepted_regions'].at(0)
end

Chef::Log.info("Cloudwatch, using region #{region}")

template node['cwlogs']['template']['temp']['path'] do
  source 'cloudwatch/cwlogs.cfg.erb'
  owner 'root'
  group 'root'
  mode 0644
end

directory install_directory do
  recursive true
end

remote_file local_script do
  source node['cwlogs']['install']['script']['url']
  mode '0755'
  action node['cwlogs']['attempt_upgrade'] ? :create : :create_if_missing
  retries 5
end

execute 'Install CloudWatch Logs agent' do
  command "#{local_script} -n -r #{region} -c #{node['cwlogs']['template']['temp']['path']}"
  not_if { Mixlib::ShellOut.new('pgrep -f aws-logs-agent-setup').run_command.exitstatus == 0 }
end
