#
# Cookbook:: kosmos_encfs
# Recipe:: default
#
# The MIT License (MIT)
#
# Copyright:: 2020, Kosmos Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

encfs_data_bag_item = data_bag_item("credentials", "encfs")
encfs_password = encfs_data_bag_item["password"]

package "encfs"

encrypted_directory = "/usr/local/lib/encrypted_data"
mount_directory = node["kosmos_encfs"]["data_directory"]

template "/usr/local/bin/mount_encfs" do
  source "mount_encfs.erb"
  mode "0755"
  variables encrypted_directory: encrypted_directory,
            mount_directory: mount_directory
end

template "/usr/local/bin/unmount_encfs" do
  source "unmount_encfs.erb"
  mode "0700"
  variables mount_directory: mount_directory
end

execute "systemctl daemon-reload" do
  command "systemctl daemon-reload"
  action :nothing
end

directory mount_directory do
  action :create
  mode "0755"
end

# FIXME the password that is stored using this script does not match the actual password
# execute "create encrypted file system" do
#   command <<-EOF
# echo "y\\\n
# y\\\n
# FIXME paranoia mode breaks hard links, which postgres relies on
# p\\\n
# #{encfs_password}\\\n
# #{encfs_password}\\\n
# " | encfs #{encrypted_directory} #{mount_directory} --public --stdinpass
#   EOF
#   sensitive true
#   not_if { ::File.exist?(encrypted_directory) }
# end

# FIXME there seems to be half a comment missing here
# The service will automatically 
cookbook_file "/lib/systemd/system/encfs.service" do
  source "encfs.service"
  notifies :run, "execute[systemctl daemon-reload]", :delayed
end
