#
# Cookbook:: irrigate-orchard_base
# Recipe:: aide_update
#
# This recipe manages running AIDE updates on a schedule.

if platform_family?('rhel', 'amazon', 'debian')

  aide_update_script = '/usr/local/bin/aide_update_script.sh'

  template aide_update_script do
    source 'aide_update_script.sh.erb'
    mode '0755'
  end

  cron_hour = '6'
  cron_minute = '0'

  if node['aide_update']['staggered'] == true

    # Helper method to determine if name ends in a number
    def number?(string)
      Float(string) && true
    rescue ArgumentError => e
      puts "Not a number: #{e}"
      false
    end

    if number?(node.name[-1..-1])
      cron_day = node.name[-1..-1].to_i
      # Make sure value corresponds to a day of the week
      cron_day > 6 && cron_day = (cron_day / 2).floor
    else
      # If name does not end in a number, pick a random day
      cron_day = rand(6)
    end
  else
    # If not staggered, pick a random day
    cron_day = rand(6)
  end

  aide_update_user = 'root'

  # Script sleeps a random amount of time, so we don't care about minute/hour
  cron 'aide_update' do
    minute cron_minute
    hour cron_hour
    weekday cron_day
    user aide_update_user
    path '/bin:/sbin:/usr/bin:/usr/sbin'
    shell '/bin/bash'
    command aide_update_script
    not_if do
      File.open("/var/spool/cron/#{aide_update_user}", File::CREAT) do |file|
        file.find { |line| line =~ /#{Regexp.quote(aide_update_script)}/ }
      end
    end
  end

  unless node['aide_update']['excluded_directories'].empty?
    template '/etc/aide/aide.conf.d/10_custom_exclusions' do
      source 'aide_custom_exclusions.erb'
      mode '0644'
    end
  end

end
