#
# Cookbook:: kosmos-bitcoin
# Recipe:: c-lightning
#

build_essential
include_recipe "git"

%w{
  autoconf automake libtool libgmp-dev libsqlite3-dev
  python3 python3-mako net-tools zlib1g-dev
  libsodium-dev gettext
}.each do |pkg|
  apt_package pkg
end

git node['c-lightning']['source_dir'] do
  repository node['c-lightning']['repo']
  revision node['c-lightning']['revision']
  action :sync
  notifies :run, 'bash[compile_c-lightning]', :immediately
end

bash "compile_c-lightning" do
  cwd node['c-lightning']['source_dir']
  code <<-EOH
    systemctl stop lightningd.service
    ./configure
    make
    make install
  EOH
  environment "PYTHON_VERSION" => "3"
  action :nothing
  notifies :restart, "systemd_unit[lightningd.service]", :delayed
end

bitcoin_user  = node['bitcoin']['username']
bitcoin_group = node['bitcoin']['usergroup']
lightning_dir = node['c-lightning']['lightning_dir']

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

directory lightning_dir do
  owner bitcoin_user
  group bitcoin_group
  mode '0750'
  action :create
end

template "#{lightning_dir}/config" do
  source "c-lightning.config.erb"
  owner bitcoin_user
  group bitcoin_group
  mode '0640'
  variables lighting_dir: lightning_dir,
            lightning_alias: node['c-lightning']['alias'],
            lightning_rgb: node['c-lightning']['rgb'],
            lightning_log_level: node['c-lightning']['log_level'],
            bitcoin_datadir: node['bitcoin']['datadir'],
            bitcoin_rpc_user: node['bitcoin']['conf']['rpcuser'],
            bitcoin_rpc_password: bitcoin_credentials["rpcpassword"],
            bitcoin_rpc_host: node['bitcoin']['conf']['rpcbind'],
            public_ip: node['c-lightning']['public_ip']
  notifies :restart, "systemd_unit[lightningd.service]", :delayed
end

systemd_unit 'lightningd.service' do
  content({
    Unit: {
      Description: 'C-Lightning daemon',
      Documentation: ['https://github.com/ElementsProject/lightning'],
      Requires: 'bitcoind.service',
      After: 'bitcoind.service'
    },
    Service: {
      User: bitcoin_user,
      Group: bitcoin_group,
      Type: 'simple',
      ExecStart: '/usr/local/bin/lightningd',
      Restart: 'always',
      RestartSec: '30',
      TimeoutSec: '240',
      PrivateTmp: true,
      ProtectSystem: 'full',
      NoNewPrivileges: true,
      PrivateDevices: true,
      MemoryDenyWriteExecute: true
    },
    Install: {
      WantedBy: 'multi-user.target'
    }
  })
  verify false
  triggers_reload true
  action [:create, :enable, :start]
end

firewall_rule 'lightningd' do
  port     [9735] # TODO use attribute
  protocol :tcp
  command  :allow
end
