#
# 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'

group "sockethub" do
  gid 7625
end

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

path_to_deploy = "/opt/sockethub"
application path_to_deploy do
  owner "sockethub"
  group "sockethub"

  git do
    user  "sockethub"
    group "sockethub"
    repository 'https://github.com/sockethub/sockethub.git'
    revision   node['sockethub']['revision']
  end

  npm_install do
    user  "sockethub"
  end

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

  template "/lib/systemd/system/sockethub_nodejs.service" do
    source 'nodejs.systemd.service.erb'
    owner 'root'
    group 'root'
    mode '0644'
    variables(
      user: "sockethub",
      group: "sockethub",
      app_dir: path_to_deploy,
      entry: "/usr/bin/node /usr/bin/npm start",
      environment: { 'DEBUG' => '*',
                     'PORT' => node['sockethub']['port'],
                     # Use the second database (index starts at 0)
                     'REDIS_URL' => "redis://localhost:6379/1" }
    )
    notifies :run, "execute[systemctl daemon-reload]", :delayed
    notifies :restart, "service[sockethub_nodejs]", :delayed
  end

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