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

require 'etc'

rmt_path = File.expand_path('..', __dir__)
require_relative '../config/boot'
$LOAD_PATH.unshift File.join(rmt_path, 'lib')

require 'active_support'
require 'active_record'
require 'erb'
require 'yaml'
require 'rmt/config'

# don't run as root
if Process.euid == 0
  # set group and then user, otherwise user cannot change group
  Process::Sys.setegid(Etc.getgrnam(RMT::DEFAULT_GROUP).gid)
  Process::Sys.seteuid(Etc.getpwnam(RMT::DEFAULT_USER).uid)
end

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

# FIXME: this check (or its message) is not correct. It already complains when the folder does just not exist, even-though it is perfectly writeable by my user.
unless File.writable?(RMT::DEFAULT_MIRROR_DIR)
  warn "Mirroring base directory (#{RMT::DEFAULT_MIRROR_DIR}) is not writable by user '#{Etc.getpwuid(Process.euid).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
