#
# Cookbook Name:: sockethub
# Recipe:: default
#
# The MIT License (MIT)
#
# Copyright:: 2019, Kosmos Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

include_recipe 'kosmos-nodejs'
include_recipe 'kosmos-redis'

user  = "sockethub"
group = "sockethub"
entry = "/usr/bin/sockethub"

group group do
  gid 7625
end

user user do
  comment     "sockethub user"
  uid         7625
  gid         7625
  manage_home true
  shell       "/bin/bash"
end

npm_package "sockethub" do
  version node['sockethub']['version']
end

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

environment_variables = {
  'PORT' => node['sockethub']['port'],
  # Use the second database (index starts at 0)
  'REDIS_URL' => "redis://localhost:6379/1"
}
unless node['sockethub']['debug_logs'].nil?
  environment_variables['DEBUG'] = node['sockethub']['debug_logs']
end

environment = environment_variables.map{|k, v| "'#{k}=#{v}'"}.join(' ')

systemd_unit "sockethub_nodejs.service" do
  content <<-EOF
[Unit]
Description=Start sockethub
Requires=redis-server.service
After=redis-server.service

[Service]
ExecStart=#{entry}
User=#{user}
Group=#{group}
Environment=#{environment}
Restart=always

[Install]
WantedBy=multi-user.target
  EOF
  triggers_reload true
  action [:create, :enable, :start]
end
