#
# Cookbook:: kosmos-bitcoin
# Recipe:: rtl
#

include_recipe 'kosmos-nodejs'

app_name      = "rtl"
rtl_dir       = "/opt/#{app_name}"
lnd_dir       = node['lnd']['lnd_dir']
bitcoin_user  = node['bitcoin']['username']
bitcoin_group = node['bitcoin']['usergroup']
credentials   = Chef::EncryptedDataBagItem.load('credentials', 'rtl')

rtl_config = {
  host: node['rtl']['host'],
  port: node['rtl']['port'],
  defaultNodeIndex: 1,
  SSO: {
    rtlSSO: 0,
    rtlCookiePath: "",
    logoutRedirectLink: ""
  },
  nodes: [
    {
      index: 1,
      lnNode: node['lnd']['alias'],
      lnImplementation: "LND",
      Authentication: {
        macaroonPath: "#{lnd_dir}/data/chain/bitcoin/mainnet",
        configPath: "#{lnd_dir}/lnd.conf"
      },
      Settings: {
        userPersona: "MERCHANT",
        themeMode: "NIGHT",
        themeColor: "TEAL",
        channelBackupPath: "",
        enableLogging: true,
        lnServerUrl: "https://localhost:8080",
        fiatConversion: true,
        currencyUnit: "EUR"
      }
    }
  ],
  multiPassHashed: credentials["multiPassHashed"]
}.to_json

application rtl_dir do
  owner bitcoin_user
  group bitcoin_group

  git do
    user  bitcoin_user
    group bitcoin_group
    repository node['rtl']['repo']
    revision node['rtl']['revision']
    notifies :restart, "systemd_unit[rtl.service]", :delayed
  end

  npm_install do
    user bitcoin_user
  end

  file "#{rtl_dir}/RTL-Config.json" do
    owner bitcoin_user
    group bitcoin_group
    mode '0640'
    content rtl_config
    notifies :restart, "systemd_unit[rtl.service]", :delayed
  end

  systemd_unit 'rtl.service' do
    content({
      Unit: {
        Description: 'Ride The Lightning',
        Documentation: ['https://github.com/Ride-The-Lightning/RTL'],
        Requires: 'lnd.service',
        After: 'lnd.service'
      },
      Service: {
        User: bitcoin_user,
        Group: bitcoin_group,
        Type: 'simple',
        # ExecStartPre: '/bin/sleep 120',
        ExecStart: "/usr/bin/node #{rtl_dir}/rtl.js",
        Restart: 'always',
        RestartSec: '30',
        TimeoutSec: '120',
        PrivateTmp: true,
        ProtectSystem: 'full',
        NoNewPrivileges: true,
        PrivateDevices: true,
      },
      Install: {
        WantedBy: 'multi-user.target'
      }
    })
    verify false
    triggers_reload true
    action [:create, :enable, :start]
  end
end

include_recipe 'firewall'
firewall_rule 'rtl_private' do
  port     node['rtl']['port'].to_i
  source   "10.1.1.0/24"
  protocol :tcp
  command  :allow
end
