#!/bin/bash

# omarchy:summary=Print debugging information
# omarchy:args=[--no-sudo] [--print]
# omarchy:examples=omarchy debug --print --no-sudo
# omarchy:requires-sudo=true

# Fedora fork: package queries use rpm, and the log is never uploaded to
# logs.omarchy.org (upstream's support service for Arch-based Omarchy).

NO_SUDO=false
PRINT_ONLY=false

while (( $# > 0 )); do
  case "$1" in
    --no-sudo)
      NO_SUDO=true
      shift
      ;;
    --print)
      PRINT_ONLY=true
      shift
      ;;
    *)
      echo "Unknown option: $1"
      echo "Usage: omarchy-debug [--no-sudo] [--print]"
      exit 1
      ;;
  esac
done

LOG_FILE="/tmp/omarchy-debug.log"

if [[ $NO_SUDO = "true" ]]; then
  DMESG_OUTPUT="(skipped - --no-sudo flag used)"
else
  DMESG_OUTPUT="$(sudo dmesg)"
fi

cat > "$LOG_FILE" <<EOF
Date: $(date)
Hostname: $(hostname)
Omarchy Package: $(rpm -q omarchy 2>/dev/null || echo "unknown")

=========================================
SYSTEM INFORMATION
=========================================
$(inxi -Farz)

=========================================
DMESG
=========================================
$DMESG_OUTPUT

=========================================
JOURNALCTL (CURRENT BOOT, WARNINGS+ERRORS)
=========================================
$(journalctl -b -p 4..1)

=========================================
INSTALLED PACKAGES
=========================================
$(dnf repoquery --userinstalled --qf '%{name} %{evr} (%{from_repo})\n' 2>/dev/null | sort)
EOF

if [[ $PRINT_ONLY = "true" ]]; then
  cat "$LOG_FILE"
  exit 0
fi

OPTIONS=("View log" "Save in current directory")

ACTION=$(gum choose "${OPTIONS[@]}")

case "$ACTION" in
  "View log")
    less "$LOG_FILE"
    ;;
  "Save in current directory")
    cp "$LOG_FILE" "./omarchy-debug.log"
    echo "✓ Log saved to $(pwd)/omarchy-debug.log"
    ;;
esac
