#
# Cookbook:: kosmos-bitcoin
# Recipe:: nbxplorer
#

build_essential

include_recipe "git"

git node['nbxplorer']['source_dir'] do
  repository node['nbxplorer']['repo']
  revision node['nbxplorer']['revision']
  action :sync
  notifies :stop, "systemd_unit[nbxplorer.service]", :immediately
  notifies :run, 'bash[build_nbxplorer]', :immediately
end

bash 'build_nbxplorer' do
  cwd node['nbxplorer']['source_dir']
  code './build.sh'
  action :nothing
end

bitcoin_credentials = Chef::EncryptedDataBagItem.load('credentials', 'bitcoin')

directory "/home/#{node['bitcoin']['username']}/.nbxplorer" do
  owner node['bitcoin']['username']
  group node['bitcoin']['usergroup']
  mode '0750'
  recursive true
end

directory File.dirname(node['nbxplorer']['config_path']) do
  owner node['bitcoin']['username']
  group node['bitcoin']['usergroup']
  mode '0750'
  recursive true
end

template node['nbxplorer']['config_path'] do
  source "nbxplorer-settings.config.erb"
  owner node['bitcoin']['username']
  group node['bitcoin']['usergroup']
  mode '0640'
  variables bitcoin_rpc_user: node['bitcoin']['conf']['rpcuser'],
            bitcoin_rpc_password: bitcoin_credentials["rpcpassword"],
            bitcoin_rpc_url: "http://#{node['bitcoin']['conf']['rpcbind']}",
            nbxplorer_port: node['nbxplorer']['port']
end

directory '/run/nbxplorer' do
  owner node['bitcoin']['username']
  group node['bitcoin']['usergroup']
  mode '0640'
end

systemd_unit 'nbxplorer.service' do
  content({
    Unit: {
      Description: 'NBXplorer daemon',
      Documentation: ['https://github.com/dgarage/NBXplorer'],
      Requires: 'bitcoind.service',
      After: 'bitcoind.service'
    },
    Service: {
      User: node['bitcoin']['username'],
      Group: node['bitcoin']['usergroup'],
      Type: 'simple',
      ExecStart: "/usr/bin/dotnet '#{node['nbxplorer']['source_dir']}/NBXplorer/bin/Release/netcoreapp3.1/NBXplorer.dll' -c #{node['nbxplorer']['config_path']} --noauth",
      PIDFile: '/run/nbxplorer/nbxplorer.pid',
      Restart: 'on-failure',
      PrivateTmp: true,
      ProtectSystem: 'full',
      NoNewPrivileges: true,
      PrivateDevices: true
    },
    Install: {
      WantedBy: 'multi-user.target'
    }
  })
  verify false
  triggers_reload true
  action [:create, :enable, :start]
end
