#!/usr/bin/env ruby
require 'optparse'
require 'json'
require 'puppet_metadata'

PidfileWorkaround = Object.new

options = {
  beaker_use_fqdn: false,
  beaker_pidfile_workaround: false,
  domain: nil,
  minimum_major_puppet_version: nil,
}

OptionParser.new do |opts|
  opts.accept(PidfileWorkaround) do |value|
    case value
    when 'true'
      true
    when 'false'
      false
    else
      value.split(',')
    end
  end

  opts.banner = "Usage: #{$0} [options] metadata"

  opts.on('--[no-]use-fqdn', 'Generate beaker setfiles with a FQDN') { |opt| options[:beaker_use_fqdn] = opt }
  opts.on('--pidfile-workaround VALUE', 'Generate the systemd PIDFile workaround to work around a docker bug', PidfileWorkaround) { |opt| options[:beaker_pidfile_workaround] = opt }
  opts.on('-d', '--domain VALUE', 'the domain for the box, only used when --use-fqdn is set to true') { |opt| options[:domain] = opt }
  opts.on('--minimum-major-puppet-version VERSION', "Don't create actions for Puppet versions less than this major version") { |opt| options[:minimum_major_puppet_version] = opt }
end.parse!

filename = ARGV[0]
filename = 'metadata.json' if filename.nil? || filename.empty?

begin
  metadata = PuppetMetadata.read(filename)
rescue StandardError => e
  warn "Failed to read #{filename}: #{e}"
  exit 2
end

github_output = ENV['GITHUB_OUTPUT'].nil? ? $stdout : File.open(ENV.fetch('GITHUB_OUTPUT', nil), 'a')
metadata.github_actions(options).outputs.each do |name, value|
  github_output.write("#{name}=#{value.to_json}\n")
end
github_output.close
