#
# Cookbook:: irrigate-trend-micro
# Recipe:: default
#
# Copyright: The Orchard
#

if node.attribute?('ec2')
  if node['trend_micro']['ds_agent_credentials_data_bag_name'] && !node['trend_micro']['ds_agent_credentials_data_bag_name'].empty?
    ds_agent_credentials = data_bag_item('secrets', node['trend_micro']['ds_agent_credentials_data_bag_name'])
    node.default['trend_micro']['ds_agent_tenant_id']      = ds_agent_credentials['ds_agent_tenant_id'].chomp
    node.default['trend_micro']['ds_agent_token']          = ds_agent_credentials['ds_agent_token'].chomp
    node.default['trend_micro']['ds_agent_api_secret_key'] = ds_agent_credentials['ds_agent_api_secret_key'].chomp
  end

  # Install Trend Micro Deep Security API
  # urllib3 version 2+ requires openssl 1.1+ so we need to explicitly install an old version
  python_packages = %w(
    urllib3==1.26.15
    deep-security-api
  )

  python_packages.each do |name|
    execute 'install_package' do
      command "/usr/bin/pip3 install -i #{node['trend_micro']['pypi_repo']} #{name}"
      not_if "/usr/bin/pip3 list | grep -i #{name}"
    end
  end

  deploy_agent_script_directory = '/usr/local'
  template "#{deploy_agent_script_directory}/tmds_get_deploy_script.py" do
    source 'tmds_get_deploy_script.py.erb'
    owner 'root'
    group 'root'
    mode  '0755'
    sensitive true
  end

  # Generate a Trend Micro deployment script via python script using API.
  deploy_agent_script = "#{deploy_agent_script_directory}/tmds_get_deploy_script.py"
  execute 'get_deployment_script' do
    command "python3 #{deploy_agent_script}"
    cwd '/usr/local'
    notifies :run, 'execute[deploy_agent]', :immediately
    action :nothing
  end

  file '/usr/local/deploy.sh' do
    action :create_if_missing
    mode '0755'
    notifies :run, 'execute[get_deployment_script]', :immediately
  end

  # Execute agent deployment script
  execute 'deploy_agent' do
    command '/bin/sh /usr/local/deploy.sh'
    notifies :run, 'execute[tmds_activation]', :immediately
    action :nothing
  end

  # Activate Trend Micro Deep Security agent
  policy_hash = node['trend_micro']['policy']
  policy_id = policy_hash[node['trend_micro']['policy_name'].to_s]
  execute 'tmds_activation' do
    command "sleep 15 && /bin/sh #{node['trend_micro']['ds_agent_home']}/dsa_control -r && /bin/sh #{node['trend_micro']['ds_agent_home']}/dsa_control -a #{node['trend_micro']['ds_activation_url']} \"tenantID:#{node['trend_micro']['ds_agent_tenant_id']}\" \"token:#{node['trend_micro']['ds_agent_token']}\" \"policyid:#{policy_id}\""
    sensitive true
    action :nothing
  end
end
