resource_name :install_ossec

property :packages, Array, required: true, default: %w(gcc make)
property :wazuh_url, String, required: true
property :wazuh_version, String, required: true
property :inotify_url, String, required: true
property :inotify_version, String, required: true
property :tmp_dir, String, required: true, default: '/ossec_tmp'
property :ossec_conf, String, required: true, default: 'ossec/preloaded-vars.conf.erb'

default_action :nothing

action :run do
  inotify_default_dir = "inotify-tools-#{inotify_version}"
  inotify_filename = "#{inotify_default_dir}.tar.gz"

  packages.each do |pkg|
    package pkg
  end

  directory tmp_dir unless Dir.exist? tmp_dir

  remote_file "#{tmp_dir}/#{wazuh_version}.tar.gz" do
    source wazuh_url
    owner 'root'
    group 'root'
    mode '0755'
    action :create_if_missing
    not_if "test -f #{tmp_dir}/#{wazuh_version}.tar.gz"
  end

  execute 'unpack wazuh' do
    command "tar -xvzf #{tmp_dir}/#{wazuh_version}.tar.gz -C #{tmp_dir}/ --strip-components=1"
    not_if "test -f #{tmp_dir}/install.sh"
  end

  execute 'remove wazuh tar file' do
    command "rm #{tmp_dir}/#{wazuh_version}.tar.gz"
    only_if "test -f #{tmp_dir}/#{wazuh_version}.tar.gz"
  end

  remote_file "#{Chef::Config[:file_cache_path]}/#{inotify_filename}" do
    source inotify_url
    owner 'root'
    group 'root'
    mode '0755'
    action :create_if_missing
    not_if "test -f #{Chef::Config[:file_cache_path]}/#{inotify_filename}"
  end

  execute 'unpack inotify' do
    command "tar -xvzf #{Chef::Config[:file_cache_path]}/#{inotify_filename} -C #{Chef::Config[:file_cache_path]}/"
    not_if "test -d #{Chef::Config[:file_cache_path]}/#{inotify_default_dir}"
  end

  execute 'configure inotify' do
    command './configure'
    cwd "#{Chef::Config[:file_cache_path]}/#{inotify_default_dir}"
  end

  execute 'make inotify' do
    command 'make'
    cwd "#{Chef::Config[:file_cache_path]}/#{inotify_default_dir}"
  end

  execute 'make install inotify' do
    command 'make install'
    cwd "#{Chef::Config[:file_cache_path]}/#{inotify_default_dir}"
  end

  execute 'remove inotify tar file' do
    command "rm #{Chef::Config[:file_cache_path]}/#{inotify_filename}"
    only_if "test -f #{Chef::Config[:file_cache_path]}/#{inotify_filename}"
  end

  template "#{tmp_dir}/etc/preloaded-vars.conf" do
    source ossec_conf
  end

  execute 'install ossec' do
    command './install.sh'
    cwd tmp_dir
  end

  execute 'enable ossec chkconfig' do
    command 'chkconfig ossec on'
  end
end
