#!/usr/bin/ruby.ruby4.0 
# frozen_string_literal: true

# Copyright (c) [2024-2026] SUSE LLC
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, contact SUSE LLC.
#
# To contact SUSE LLC about this file by physical or electronic mail, you may
# find current contact information at www.suse.com.

$LOAD_PATH.unshift File.expand_path("../lib", __dir__)

# Make the vendored YaST/AutoYaST modules (service/YaST2/modules) discoverable through
# Yast.import, the same way lib/agama/y2dir is used to override Yast::Package. See
# YaST2/README.md for details.
#
# IMPORTANT: this must happen *before* "yast" is required. The Y2DIR search path list is
# read from the environment and cached (in C++, see Y2PathSearch::initializePaths()) the
# first time it is needed, which happens as a side effect of loading the "yast" gem/its
# native extension. Setting Y2DIR afterwards is silently ignored.
agama_y2dir = File.expand_path("../YaST2", __dir__)
ENV["Y2DIR"] = [ENV.fetch("Y2DIR", nil), agama_y2dir].compact.join(":")

# Set the PATH to a known value
ENV["PATH"] = "/sbin:/usr/sbin:/usr/bin:/bin"

require "yast"

# Disable AutoYaST XML validation. It will be enabled in the future.
ENV["YAST_SKIP_XML_VALIDATION"] = "1"

require "rubygems"
# find Gemfile when D-Bus activates a git checkout
Dir.chdir(__dir__) do
  require "bundler/setup"
end

require "agama/commands/agama_autoyast"

if ARGV.length != 2
  warn "Usage: #{$PROGRAM_NAME} URL DIRECTORY"
  exit 1
end

begin
  url, directory = ARGV
  result = Agama::Commands::AgamaAutoYaST.new(url, directory).run
  if !result
    warn "Did not convert the profile (canceled by the user)."
    exit 2
  end
rescue Agama::Commands::CouldNotFetchProfile => e
  warn "Could not fetch the AutoYaST profile:\n\n"
  warn e.full_message
  exit 3
rescue Agama::Commands::CouldNotWriteAgamaConfig => e
  warn "Could not write the Agama configuration:\n\n"
  warn e.full_message
  exit 4
rescue Agama::Commands::ProfileNotFound => e
  warn "Could not find the AutoYaST profile"
  exit 5
end
