#! /usr/bin/ruby.ruby3.4 --encoding=utf-8
# Note: The ruby interpreter path above is replaced at the installation
# to use a hardcoded versioned path.

# set env as first part, otherwise dummy UI will be created.
# for insts-sys it will be overwritten later
ENV["YAST_IS_RUNNING"] = "yes"

require "socket"

require "yast"
require "yast/y2start_helpers"

Yast::Y2StartHelpers.setup_signals

# Configure global YaST environment. For example, it sets $PATH to ensure that
# external commands are only executed from safe paths.
Yast::Y2StartHelpers.config_env

File.umask(0o022)

Yast.y2milestone("y2base called with #{ARGV.inspect}")

begin
  args = Yast::Y2StartHelpers.parse_arguments(ARGV.dup)
rescue RuntimeError => e
  $stderr.puts e
  $stderr.puts Yast::Y2StartHelpers.help
  exit 1
end

if args[:generic_options][:help]
  $stdout.puts Yast::Y2StartHelpers.help
  exit 0
end

if args[:client_name] == "installation" &&
    args[:client_options][:params].include?("initial")
  ENV["YAST_IS_RUNNING"] = "instsys"
end

if !Yast::WFM.ClientExists(args[:client_name])
  $stderr.puts "No such client module #{args[:client_name]}"
  exit 1
end

NO_CLI_CLIENTS = ["installation", "view_anymsg", "firstboot", "scc"].freeze
Yast.ui_create(args[:server_name], args[:server_options])
# set application title bsc#1033161
Yast.import "UI"

# set title only if it is not CLI (bsc#1033993)
# modules do not have CLI arguments, except installation (bsc#1037891)
set_title = args[:client_options][:params].empty? || NO_CLI_CLIENTS.include?(args[:client_name])
Yast::UI.SetApplicationTitle(
  Yast::Y2StartHelpers.application_title(args[:client_name])) if set_title

target_dir = ENV["YAST_SCR_TARGET"] || ""
if !target_dir.empty? && target_dir != "/"
  if File.directory?(target_dir)
    Yast::Y2StartHelpers.redirect_scr(target_dir)
  else
    abort "Cannot set the target, directory #{target_dir} not found"
  end
end

exit Yast::Y2StartHelpers.generate_exit_code(
  Yast::WFM.CallFunction(args[:client_name], args[:client_options][:params])
)
