#
# Cookbook:: kosmos-akkounts
# Recipe:: default
#
require 'ipaddr'

app_name     = "akkounts"
deploy_user  = "deploy"
deploy_group = "deploy"
deploy_path  = "/opt/#{app_name}"
credentials  = Chef::EncryptedDataBagItem.load('credentials', app_name)

group deploy_group

user deploy_user do
  group       deploy_group
  manage_home true
  shell       "/bin/bash"
end

package "libpq-dev"

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

npm_package "yarn" do
  version "1.22.4"
end

ruby_version = "2.6.6"
bundle_path = "/opt/ruby_build/builds/#{ruby_version}/bin/bundle"
rails_env = node.chef_environment == "development" ? "development" : "production"

systemd_unit "akkounts.service" do
  content({
    Unit: {
      Description: "Kosmos Accounts",
      Documentation: ["https://gitea.kosmos.org/kosmos/akkounts"],
      After: "network.target"
    },
    Service: {
      Type: "simple",
      User: deploy_user,
      WorkingDirectory: deploy_path,
      Environment: "RAILS_ENV=#{rails_env}",
      ExecStart: "#{bundle_path} exec puma -C config/puma.rb --pidfile #{deploy_path}/tmp/puma.pid",
      ExecStop: "#{bundle_path} exec puma -C config/puma.rb --pidfile #{deploy_path}/tmp/puma.pid stop",
      ExecReload: "#{bundle_path} exec pumactl -F config/puma.rb --pidfile #{deploy_path}/tmp/puma.pid phased-restart",
      PIDFile: "#{deploy_path}/tmp/puma.pid",
      TimeoutSec: "10",
      Restart: "always",
    },
    Install: {
      WantedBy: "multi-user.target"
    }
  })
  verify false
  triggers_reload true
  action [:create, :enable]
end

systemd_unit "akkounts-sidekiq.service" do
  content({
    Unit: {
      Description: "Kosmos Accounts async/background jobs",
      Documentation: ["https://gitea.kosmos.org/kosmos/akkounts"],
      Requires: "redis-server.service",
      After: "syslog.target network.target redis-server.service"
    },
    Service: {
      Type: "notify",
      User: deploy_user,
      WorkingDirectory: deploy_path,
      Environment: "MALLOC_ARENA_MAX=2",
      ExecStart: "#{bundle_path} exec sidekiq -C #{deploy_path}/config/sidekiq.yml -e production",
      WatchdogSec: "10",
      Restart: "on-failure",
      RestartSec: "1",
      StandardOutput: "syslog",
      StandardError: "syslog",
      SyslogIdentifier: "sidekiq"
    },
    Install: {
      WantedBy: "multi-user.target"
    }
  })
  verify false
  triggers_reload true
  action [:create, :enable]
end

application deploy_path do
  owner deploy_user
  group deploy_group

  # Take care of application restarts manually, in the git resource
  action_on_update false

  environment "HOME" => deploy_path,
              "PATH" => "/opt/ruby_build/builds/#{ruby_version}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"

  ruby_runtime ruby_version do
    provider :ruby_build
    version ruby_version
  end

  git do
    user deploy_user
    group deploy_group
    repository node[app_name]["repo"]
    revision node[app_name]["revision"]
    # Restart services on deployments
    notifies :restart, "application[#{deploy_path}]", :delayed
  end

  file "#{deploy_path}/config/master.key" do
    content credentials['rails_master_key']
    mode '0400'
    owner deploy_user
    group deploy_group
  end

  execute "bundle install" do
    environment "HOME" => deploy_path
    user deploy_user
    cwd deploy_path
    command "/opt/ruby_build/builds/#{ruby_version}/bin/bundle install --without development,test --deployment"
  end

  execute "yarn install" do
    environment "HOME" => deploy_path, "NODE_ENV" => "production"
    user deploy_user
    cwd deploy_path
    command "yarn install --pure-lockfile"
  end

  execute 'rake db:migrate' do
    environment "RAILS_ENV" => rails_env, "HOME" => deploy_path
    user deploy_user
    group deploy_group
    cwd deploy_path
    command "PATH=\"/opt/ruby_build/builds/#{ruby_version}/bin:$PATH\" bundle exec rake db:migrate"
  end

  execute 'rake assets:precompile' do
    environment "RAILS_ENV" => rails_env, "HOME" => deploy_path
    user deploy_user
    group deploy_group
    cwd deploy_path
    command "PATH=\"/opt/ruby_build/builds/#{ruby_version}/bin:$PATH\" bundle exec rake assets:precompile"
  end

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

  service "akkounts-sidekiq" do
    action [:enable, :start]
  end
end

ejabberd_private_ip_addresses = []
search(:node, "role:ejabberd").each do |node|
  ejabberd_private_ip_addresses << node["knife_zero"]["host"]
end

ejabberd_private_ip_addresses.each do |ip_address|
  IPAddr.new ip_address
  hostsfile_entry ip_address do
    hostname 'xmpp.kosmos.org'
    action :create
  end
rescue IPAddr::InvalidAddressError
  next
end

include_recipe 'kosmos-akkounts::nginx'
