#
# Cookbook:: irrigate-orchard_base
# Recipe:: mounts
#
# Copyright: The Orchard
#
#
# Attributes should be specified in the following format:
#
# "windows_mounts": {
#   "dev_mount1": {
#     "mount_point": "/var/www/html",
#     "device": "//192.168.1.1/dir",
#     "filesystem": "cifs",
#     "credentials": "/root/.smbcred"
#   },
#   "dev_mount2": {
#     "mount_point": "/var/lib/dir",
#     "device": "//192.168.1.2/dir",
#     "filesystem": "cifs",
#     "credentials": "/root/.smbcred2"
#   }
# }
#
# "unix_mounts": {
#   "dev_nfs1": {
#     "mount_point": "/var/www/html",
#     "device": "'10.0.0.1:/nfs_share'",
#     "filesystem": "nfs"
#   },
#   "dev_xfs2": {
#     "mount_point": "/mnt/dir",
#     "device": "/dev/md0",
#     "filesystem": "xfs"
#   }
# }

if node['mounts']['windows_mounts'] && !node['mounts']['windows_mounts'].empty?
  node['mounts']['windows_mounts'].each do |_mount_name, mount_info|
    next unless mount_info['smbcred_data_bag_name']
    smbcred_config_location = mount_info['credentials']
    smbcred_credentials = data_bag_item('secrets', mount_info['smbcred_data_bag_name'])
    smb_username = smbcred_credentials['username'].chomp
    smb_password = smbcred_credentials['password'].chomp
    template smbcred_config_location do
      source 'smbcred.erb'
      owner 'root'
      group 'root'
      mode '0600'
      variables(smb_username: smb_username,
                smb_password: smb_password)
    end
  end
end

if node['mounts']['windows_mounts'] && !node['mounts']['windows_mounts'].empty?
  node['mounts']['windows_mounts'].each do |mount_name, mount_info|
    mount mount_name do
      only_if { ::File.exist?((mount_info['credentials']).to_s) }
      mount_point mount_info['mount_point']
      device mount_info['device']
      fstype mount_info['filesystem']
      options "credentials=#{mount_info['credentials']},#{mount_info['options']}"
      action [:mount, :enable]
    end
  end
else
  puts 'There are no configured Windows mounts. Moving along...'
end

if node['mounts']['unix_mounts'] && !node['mounts']['unix_mounts'].empty?
  node['mounts']['unix_mounts'].each do |mount_name, mount_info|
    mount mount_name do
      mount_point mount_info['mount_point']
      device mount_info['device']
      fstype mount_info['filesystem']
      action [:mount, :enable]
    end
  end
else
  puts 'There are no configured Unix mounts. Moving along...'
end
