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

build_essential 'hal8000' do
  compile_time true
end

include_recipe "kosmos-nodejs"
include_recipe "kosmos-redis"
include_recipe "kosmos-hubot::_user"

unless node.chef_environment == "development"
  include_recipe 'firewall'
  firewall_rule 'hubot_express_hal8000_freenode' do
    port     node['hal8000']['http_port']
    protocol :tcp
    command  :allow
  end
end

hal8000_freenode_data_bag_item = Chef::EncryptedDataBagItem.load('credentials', 'hal8000_freenode')

hal8000_path = "/opt/hal8000"
application hal8000_path do
  owner "hubot"
  group "hubot"

  git do
    user       "hubot"
    group      "hubot"
    repository "https://gitea.kosmos.org/kosmos/hal8000.git"
    revision   "master"
  end

  file "#{name}/external-scripts.json" do
    mode  "0640"
    owner "hubot"
    group "hubot"
    content [
      "hubot-help",
      "hubot-read-tweet",
      "hubot-redis-brain",
      "hubot-rules",
      "hubot-shipit",
      "hubot-plusplus",
      "hubot-tell",
      "hubot-seen",
      "hubot-incoming-webhook",
      "hubot-auth",
      "hubot-schedule"
    ].to_json
  end

  npm_install do
    user "hubot"
  end

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

  template "/lib/systemd/system/hal8000_nodejs.service" do
    source 'nodejs.systemd.service.erb'
    owner 'root'
    group 'root'
    mode '0644'
    variables(
      user: "hubot",
      group: "hubot",
      app_dir: hal8000_path,
      entry: "#{hal8000_path}/bin/hubot -a irc",
      environment: {
        # "HUBOT_LOG_LEVEL"             => "error",
        "HUBOT_IRC_SERVER"              => "irc.freenode.net",
        "HUBOT_IRC_ROOMS"               => "#5apps,#kosmos,#kosmos-dev,#kosmos-random,#remotestorage,#hackerbeach,#unhosted,#sockethub",
        "HUBOT_IRC_NICK"                => "hal8000",
        "HUBOT_IRC_NICKSERV_USERNAME"   => "hal8000",
        "HUBOT_IRC_NICKSERV_PASSWORD"   => hal8000_freenode_data_bag_item['nickserv_password'],
        "HUBOT_IRC_UNFLOOD"             => "100",
        "HUBOT_RSS_PRINTSUMMARY"        => "false",
        "HUBOT_RSS_PRINTERROR"          => "false",
        "HUBOT_RSS_IRCCOLORS"           => "true",
        "HUBOT_PLUSPLUS_POINTS_TERM"    => "karma,karma",
        "HUBOT_RSS_HEADER"              => "Update:",
        "HUBOT_AUTH_ADMIN"              => "bkero,derbumi,galfert,gregkare,slvrbckt,raucao",
        "HUBOT_HELP_REPLY_IN_PRIVATE"   => "true",
        "WEBHOOK_TOKEN"                 => hal8000_freenode_data_bag_item['webhook_token'],
        "EXPRESS_PORT"                  => node['hal8000']['http_port']
      }
    )
    notifies :run, "execute[systemctl daemon-reload]", :delayed
    notifies :restart, "service[hal8000_nodejs]", :delayed
  end

  service "hal8000_nodejs" do
    action [:enable, :start]
  end
end

