#!/bin/bash

QUTE_PIDS_FILE="/tmp/qute_tab_pids.txt"
DUMP_SCRIPT="$HOME/.local/share/qutebrowser/userscripts/dump_tab_pids.py"

# Parse arguments
SORT_BY="mem"
while getopts "rc" opt; do
    case $opt in
        r) SORT_BY="mem" ;;
        c) SORT_BY="cpu" ;;
        *) echo "Usage: top10 [-r|-c]" >&2; exit 1 ;;
    esac
done

# Refresh qutebrowser tab PIDs
if pgrep -x qutebrowser > /dev/null; then
    qutebrowser ":debug-pyeval -q exec(open('$DUMP_SCRIPT').read())" 2>/dev/null
    sleep 0.1  # give it a moment to write the file
fi

# Build associative array of PID -> tab title
declare -A tab_titles
if [[ -f "$QUTE_PIDS_FILE" ]]; then
    while IFS=$'\t' read -r pid title; do
        tab_titles[$pid]="$title"
    done < "$QUTE_PIDS_FILE"
fi

printf "%-8s %6s %6s  %s\n" "PID" "%MEM" "%CPU" "COMMAND"
ps -eo pid,%mem,%cpu,comm --sort=-"%$SORT_BY" | tail -n +2 | head -n 10 | \
    while read pid mem cpu comm; do
        if [[ "$comm" == "QtWebEngineProc" && -n "${tab_titles[$pid]}" ]]; then
            comm="qute: ${tab_titles[$pid]}"
        fi
        printf "%-8s %6s %6s  %s\n" "$pid" "$mem" "$cpu" "$comm"
    done
