#
# Cookbook:: irrigate-mysql
# Recipe:: iscsi_remount
#
# Copyright:: (C) The Orchard
#
# All rights reserved - Do Not Redistribute
#

if platform_family?('rhel')

  packages = %w(
    iscsi-initiator-utils
  )

  packages.each do |name|
    package name
  end

  service 'iscsi' do
    supports 'restart' => true, 'status' => true, 'reload' => false
    action [:enable, :start]
  end

  # Create the iscsi_remount script
  remount_script = '/root/iscsi_remount.sh'

  case node['mysql']['db_type']
  when 'art_relations'
    db_refresh_file = 'refresh_database.php'
  when 'direct_delivery'
    db_refresh_file = 'dd_refresh_database.php'
  end

  # Determine the type of db
  template remount_script do
    source 'iscsi_remount.sh.erb'
    owner 'root'
    group 'root'
    mode '0755'
    action :create
    variables db_refresh_file: db_refresh_file
  end

  if node['platform_version'].start_with?('6')

    # Manage rc.local in order to run script at boot
    template '/etc/rc.d/rc.local' do
      source 'rc.local.erb'
      owner 'root'
      group 'root'
      mode '0755'
      variables remount_script_path: remount_script
    end

  elsif node['platform_version'].start_with?('7')

    systemd_unit 'iscsi-remount.service' do
      content(
        Unit: {
          Description: 'ISCSI remount',
          After: 'network.target iscsid.service',
          StartLimitBurst: '3',
        },
        Service: {
          Type: 'simple',
          ExecStartPre: '/bin/sleep 60',
          ExecStart: remount_script,
          TimeoutStartSec: '300s',
          TimeoutStopSec: '10s',
          Restart: 'on-failure',
        },
        Install: {
          WantedBy: 'multi-user.target',
        }
      )
      action [:create, :enable]
    end
  end

  # Run script on a schedule
  cron 'iscsi_remount' do
    hour '*'
    minute '*/5'
    user 'root'
    command "/bin/bash #{remount_script}"
  end
end
