#!/usr/bin/ruby.ruby3.4 
require 'rbg'

def die
  puts "Usage: rbg run|start|stop|reload [-c config_file] [-E environment]"
  Process.exit(1)
end

begin
  args = []
  config_file = nil
  environment = nil
  
  while arg = ARGV.shift
    case arg
    when '-c'
      config_file = ARGV.shift
    when '-E', '-e'
      environment = ARGV.shift
    else
      args << arg
    end
  end
  
  command = args[0]
  if config_file.nil? && args[1]
    [args[1], "./proceses/#{args[1]}.rb", "./config/processes/#{args[1]}.rb"].each do |loc|
      if File.exist?(loc)
        config_file = loc
        break
      end
    end
  end
  
  if config_file.nil?
    if File.exist?('Rbgfile')
      config_file = "Rbgfile"
    elsif File.exist?('ProcessFile')
      config_file = "ProcessFile"
    end
  end
  
  die unless config_file
  
  case command
  when 'run'
    Rbg.start(config_file, {:background => false, :environment => environment})
  when 'start'
    Rbg.start(config_file, {:background => true, :environment => environment})
  when 'stop'
    Rbg.stop(config_file, {:environment => environment})
  when 'reload', 'restart'
    Rbg.reload(config_file, {:environment => environment})
  else
    die
  end
rescue Rbg::Error => e
  Rbg.say "!!! #{e.message}"
  Process.exit(1)
end

