#
# Cookbook Name:: kosmos-hubot
# Recipe:: wormhole
#

app_name  = "wormhole"
app_user  = "hubot"
app_group = "hubot"
app_path  = "/opt/#{app_name}"
data_bag  = Chef::EncryptedDataBagItem.load('credentials', app_name)

app_env = {
  "HUBOT_LOG_LEVEL"              => node.chef_environment == "development" ? "debug" : "info",
  "HUBOT_IRC_SERVER"             => "irc.freenode.net",
  "HUBOT_IRC_ROOMS"              => "#kosmos,#kosmos-dev,#kosmos-random,#sockethub",
  "HUBOT_IRC_NICK"               => app_name,
  "HUBOT_IRC_NICKSERV_USERNAME"  => app_name,
  "HUBOT_IRC_NICKSERV_PASSWORD"  => data_bag['nickserv_password'],
  "HUBOT_IRC_UNFLOOD"            => "100",
  "HUBOT_WORMHOLE_XMPP_JID"      => "wormhole@kosmos.org",
  "HUBOT_WORMHOLE_XMPP_PASSWORD" => data_bag['xmpp_password'],
  "HUBOT_WORMHOLE_XMPP_HOST"     => "xmpp.kosmos.org",
  "HUBOT_WORMHOLE_XMPP_PORT"     => "5222",
  "HUBOT_WORMHOLE_XMPP_NICKNAME" => "wormhole",
  "HUBOT_WORMHOLE_XMPP_ROOMS"    => "kosmos@kosmos.chat,kosmos-dev@kosmos.chat,kosmos-random@kosmos.chat,sockethub@kosmos.chat",
  "EXPRESS_PORT"                 => node['wormhole']['http_port']
}

build_essential
include_recipe "kosmos-nodejs"
include_recipe "kosmos-hubot::_user"
include_recipe "git"

git app_path do
  user app_user
  group app_group
  repository "https://gitea.kosmos.org/kosmos/wormhole.git"
  revision "master"
  action :sync
  notifies :run, "bash[npm_install_#{app_name}]", :immediately
  notifies :restart, "systemd_unit[#{app_name}.service]", :delayed
end

bash "npm_install_#{app_name}" do
  user app_user
  cwd app_path
  code 'npm install'
  action :nothing
end

file "#{app_path}/external-scripts.json" do
  mode  "0640"
  owner app_user
  group app_group
  content [].to_json
end

systemd_unit "#{app_name}.service" do
  content({
    Unit: {
      Description: "#{app_name} (node.js app)",
      Documentation: ['https://gitea.kosmos.org/kosmos/wormhole'],
    },
    Service: {
      User: app_user,
      Group: app_group,
      ExecStart: "#{app_path}/bin/hubot -a irc --name #{app_name}",
      WorkingDirectory: app_path,
      Environment: app_env.map{|k, v| "'#{k}=#{v}'"}.join(' '),
      Type: 'simple',
      Restart: 'always',
      RestartSec: '2',
      TimeoutSec: '10',
      PrivateTmp: true,
      ProtectSystem: 'full',
      NoNewPrivileges: true,
      PrivateDevices: true
    },
    Install: {
      WantedBy: 'multi-user.target'
    }
  })
  verify false
  triggers_reload true
  action [:create, :enable, :start]
end
