#!/usr/bin/env ruby
#
# After installation, this script is used to configure the system.
#
# This is really a basic script intended to get the ball rolling in the early
# stages of the project.
#
# Run this script with elevated privileges.
#

# This is really set by the installation system
INSTALL_DIR = ENV['install_dir']
raise 'install_dir not defined' if INSTALL_DIR.nil?

require 'hws_settings'

#=============================================================================
# Helper Methods
#=============================================================================

require 'ohai'

def node
  @node ||= init_system
end

def init_system
  puts 'collecting system data'
  s = Ohai::System.new
  s.all_plugins
  s
end

def centos?
  node['platform'] == 'centos'
end

def ubuntu?
  node['platform'] == 'ubuntu'
end

def centos_major_version
  node['platform_version'][/\d+/]
end

def user_exists?(username)
  system("getent passwd #{username} > /dev/null")
end

def create_user(username)
  puts "creating system user #{username}"

  home_dir = File.join(INSTALL_DIR, 'home', username)

  if centos?
    system(%W(
           useradd -r
               --shell /bin/bash
               --home #{home_dir}
               #{username}
      ).join(' '))
  else
    system(%W(adduser --system
             --group
             --home #{home_dir}
               --shell /bin/bash
             #{username}).join(' '))
  end
end

def ensure_dir_exists(dir, user)
  unless Dir.exist?(dir)
    puts "creating directory for user #{user}: #{dir}"
    FileUtils.mkpath(dir)
    FileUtils.chown(user, user, dir)
  end
end

# Make sure that the Upstart configuration file has been linked
def ensure_startup_config_exists
  unless File.exist?('/etc/init.d/helix_web_services')
    puts 'linking init.d script to /etc/init.d/helix_web_services'
    FileUtils.ln_sf("#{INSTALL_DIR}/sbin/helix_web_services", '/etc/init.d/helix_web_services')
    # TODO this is probably update-rc.d on debian, chkconfig on centos?
    # system('sudo initctl reload-configuration')
    if ubuntu?
      system('sudo update-rc.d helix_web_services defaults')
    end
  end
end

#=============================================================================
# Execution
#=============================================================================

unless user_exists?(HWSSettings.system.SYSTEM_USER)
  create_user(HWSSettings.system.SYSTEM_USER)
end

require 'fileutils'

ensure_dir_exists(HWSSettings.system.DATA_DIR, HWSSettings.system.SYSTEM_USER)
ensure_dir_exists(HWSSettings.system.LOG_DIR, HWSSettings.system.SYSTEM_USER)
ensure_dir_exists(HWSSettings.system.RUN_DIR, HWSSettings.system.SYSTEM_USER)

ensure_startup_config_exists unless ENV.key?('NO_STARTUP_CONFIG')