#!/usr/bin/env bash
set -euo pipefail

# Script Name: catbin
# Description: Display source code of executables in PATH (security auditing!)
# Source: https://evanhahn.com/scripts-i-wrote-that-i-use-all-the-time/
# Credit: Evan Hahn - https://codeberg.org/EvanHahn/dotfiles
# Usage: catbin httpstatus     # see what the httpstatus script does
#        catbin tryna           # audit the tryna script
#        catbin ls              # won't work for binaries, only scripts

if [[ $# -eq 0 ]]; then
  echo "Usage: catbin <command-name>" >&2
  echo "Example: catbin httpstatus" >&2
  exit 1
fi

cmd_path=$(command -v "$1" 2>/dev/null || true)

if [[ -z "$cmd_path" ]]; then
  echo "Command not found: $1" >&2
  exit 1
fi

# Check if it's a text file (script) or binary
if file "$cmd_path" | grep -q "text"; then
  # Use bat if available for syntax highlighting
  if command -v bat &>/dev/null; then
    bat "$cmd_path"
  else
    cat "$cmd_path"
  fi
else
  echo "Error: $cmd_path is a binary, not a script" >&2
  echo "File type: $(file "$cmd_path")" >&2
  exit 1
fi
