#!/usr/bin/env ruby

require 'pathname'

# Resolve the actual bin directory (handles symlinks from bunx/npx)
bin_dir = Pathname.new(__FILE__).realpath.dirname

command = ARGV[0]
args = ARGV[1..-1]

if command.nil? || command == '--help' || command == '-h'
  subcommands = Dir[bin_dir.join("fez-*")].map do |path|
    File.basename(path).sub(/^fez-/, '')
  end.sort

  puts "Usage: fez <command> [<args>]"
  puts ""
  puts "Available commands: #{subcommands.join(', ')}"

  subcommands.each do |cmd|
    cmd_path = bin_dir.join("fez-#{cmd}")
    help = `#{cmd_path} --help 2>&1`.strip
    next if help.empty?
    puts ""
    puts help.gsub(/^/, '  ')
  end

  exit 0
end

subcommand_path = bin_dir.join("fez-#{command}")

if File.exist?(subcommand_path) && File.executable?(subcommand_path)
  exec(subcommand_path.to_s, *args)
else
  puts "fez: '#{command}' is not a fez command. See 'fez --help'."
  exit 1
end