nfs_exports = node['nfs']['exports']
nfs_mounts = node['nfs']['mounts']

%w( nfs-utils rpcbind ).each do |pkg|
  package pkg do
    action :install
  end
end

if nfs_exports
  # Fails trying to restart service nfslock
  # include_recipe "nfs::default"

  service 'rpcbind' do
    action :restart
  end
  service 'nfs-lock' do
    action :restart
  end

  include_recipe 'nfs::server4'
  nfs_exports.each do |nfs_export_name, nfs_export|
    writeable = nfs_export['writeable']
    sync = nfs_export['sync']
    options = nfs_export['options']
    nfs_export nfs_export_name do
      network nfs_export['network']
      writeable writeable
      sync sync
      options options
    end
  end
end

if nfs_mounts
  nfs_mounts.each do |nfs_mount_name, nfs_mount|
    device = nfs_mount['device']
    options = nfs_mount['options'] || ''
    mode = nfs_mount['mode'] || '0755'
    owner = nfs_mount['owner'] || 'root'
    group = nfs_mount['group'] || 'root'
    force_chown = nfs_mount['force_chown']

    directory nfs_mount_name do
      owner owner
      group group
      mode mode
      recursive true
      action :create
      not_if { File.exist?(nfs_mount_name) }
    end

    mount nfs_mount_name do
      device device
      fstype 'nfs'
      options options
      pass 0
      action :mount
    end

    mount nfs_mount_name do
      device device
      fstype 'nfs'
      options options
      pass 0
      action :enable
      not_if "cat /etc/fstab | grep #{nfs_mount_name} | grep #{nfs_mount['device']}"
    end

    execute "force-#{nfs_mount_name}-ownership" do
      command "chown -R #{owner}:#{group} #{nfs_mount_name}"
      only_if { force_chown }
    end
  end
end
