#
# Cookbook:: irrigate-ecs
# Recipe:: ssm
#
# Copyright:: 2023, All Rights Reserved.

if platform_family?('amazon')

  # Is there a good reason to fetch the RPM from S3? If not, use the package from the AL2 core repo.
  # https://docs.aws.amazon.com/systems-manager/latest/userguide/agent-install-al2.html
  # Sample URL: https://s3.us-east-1.amazonaws.com/amazon-ssm-us-east-1/latest/linux_amd64/amazon-ssm-agent.rpm
  # Checksum: https://docs.aws.amazon.com/systems-manager/latest/userguide/verify-agent-signature.html
  package 'amazon-ssm-agent'

end

# Read SSM activation credentials from encrypted data bag, using unique secret
if !node['ssm']['activation_credentials_data_bag_name'].empty?
  if node['ssm']['use_default_data_bag_secret_file']
    ssm_activation_credentials = data_bag_item('secrets', node['ssm']['activation_credentials_data_bag_name'])
  else
    secret = IO.read(node['ssm']['activation_credentials_data_bag_encryption_secret_file']).chomp
    ssm_activation_credentials = data_bag_item('secrets', node['ssm']['activation_credentials_data_bag_name'], secret)
  end

  execute 'ssm_registration' do
    command "amazon-ssm-agent -register -code #{ssm_activation_credentials['activation_code']} -id #{ssm_activation_credentials['activation_id']} -region #{node['ssm']['region']}"
    creates '/var/lib/amazon/ssm/Vault/Store/RegistrationKey'
    notifies :restart, 'service[amazon-ssm-agent]'
    sensitive true
  end
else
  raise "node['ssm']['activation_credentials_data_bag_name'] attribute is not set or is empty"
end

# Service should only be started after registration
service 'amazon-ssm-agent' do
  action [:enable, :start]
end
