#!/usr/bin/env ruby

abort "Please use Ruby 1.9.3 or higher" if RUBY_VERSION < "1.9.3"

require 'optparse'
require 'fileutils'

if Process.uid!=0
  abort "You have to be root to install the OMF RC startup script and config file.
You also need to have the omf_rc gem installed as root and have RVM installed as root (if you don't use system ruby)."
end

options = {}
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: #{File.basename($PROGRAM_NAME)} [options]"
  opts.on("-i", "--initscript", "Install init script to run the OMF RC on boot (as root)") do |i|
    options[:init] = i
  end
  opts.on("-c", "--configfile", "Install config file template in /etc/omf_rc/config.yml") do |c|
    options[:config] = c
  end
  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end
end

optparse.parse!
if options.empty?
  puts optparse
  exit
end

spec = Gem::Specification.find_by_name("omf_rc")
gem_root = spec.gem_dir

if options[:config]
  puts "Copying configuration file..."
  FileUtils.mkdir_p "/etc/omf_rc"
  FileUtils.cp "#{gem_root}/config/config.yml", "/etc/omf_rc/config.yml"
  FileUtils.chmod 0644, "/etc/omf_rc/config.yml"
  puts "done."
end

if options[:init]
  puts "Detecting operating system..."
  FileUtils.cp "#{gem_root}/init/run_omf_rc.sh", "/usr/local/bin/run_omf_rc.sh"
  if !File.exist?("/etc/issue")
    abort "Unknown or unsupported operating system. Cannot install init script."
  end
  issue = File.read("/etc/issue")
  if issue.include? "Ubuntu"
    FileUtils.cp "#{gem_root}/init/ubuntu", "/etc/init/omf_rc.conf"
    puts "Upstart script for Ubuntu has been installed. Execute 'start omf_rc' to run the daemon."
  elsif issue.include? "Debian"
    FileUtils.cp "#{gem_root}/init/debian", "/etc/init.d/omf_rc"
    `update-rc.d omf_rc defaults`
    puts "Init script for Debian has been installed. Execute '/etc/init.d/omf_rc start' to run the daemon."
  elsif issue.include? "Angstrom"
    FileUtils.cp "#{gem_root}/init/angstrom", "/etc/init.d/omf_rc"
    `update-rc.d omf_rc defaults`
    puts "Init script for Angstrom has been installed. Execute '/etc/init.d/omf_rc start' to run the daemon."
  elsif issue.include? "Fedora"
     FileUtils.cp "#{gem_root}/init/fedora", "/etc/init.d/omf_rc"
    `chkconfig --add omf_rc`
    # older Fedora's don't use systemd
    `systemctl --system daemon-reload` if File.exist?("/bin/systemctl")
    puts "Init script for Fedora has been installed. Execute '/etc/init.d/omf_rc start' to run the daemon."
  else
    abort "OS '#{os}' is not supported. Cannot install init script."
  end
end