#!/usr/bin/ruby.ruby2.5

rmt_path = File.expand_path('..', __dir__)
require_relative '../config/boot'

$LOAD_PATH.unshift File.join(rmt_path, 'lib')

require 'etc'
require 'active_support'
require 'active_support/core_ext/string'
require 'active_record'
require 'erb'
require 'yaml'
require 'rmt/config'
require_relative '../config/initializers_cli/disable_deprecation_warnings'
require_relative '../config/initializers_cli/rmt_fast_gettext'
require_relative '../config/initializers_cli/rmt_fast_gettext_cli_locale'

relative_load_paths = %w[lib lib/rmt app/models app/services app/validators].map { |dir| File.join(rmt_path, dir) }
ActiveSupport::Dependencies.autoload_paths += relative_load_paths

if RMT::CLI::Base.process_user_name == 'root'
  # set group and then user, otherwise user cannot change group
  Process::Sys.setegid(Etc.getgrnam(RMT::DEFAULT_GROUP).gid)
  # GPG needs ruid to be set
  Process::Sys.setuid(Etc.getpwnam(RMT::DEFAULT_USER).uid)
  Process::Sys.seteuid(Etc.getpwnam(RMT::DEFAULT_USER).uid)
end

if File.exist?(RMT::DEFAULT_MIRROR_DIR) && !File.writable?(RMT::DEFAULT_MIRROR_DIR)
  warn "Mirroring base directory (#{RMT::DEFAULT_MIRROR_DIR}) is not writable by user '#{RMT::CLI::Base.process_user_name}'"
  warn 'Run as root or adjust the permissions.'
  exit RMT::CLI::Error::ERROR_OTHER
end

db_config = RMT::Config.db_config
ActiveRecord::Base.establish_connection(db_config)

begin
  RMT::CLI::Main.start(ARGV)
rescue Interrupt
  abort "\nInterrupted! You might need to rerun this command to have a consistent state."
end
