#!/bin/bash

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

printf "%-8s %-28s %s\n" "PID" "PACKAGE" "COMMAND"
printf "%-8s %-28s %s\n" "--------" "----------------------------" "----------------------------------------"

declare -A cache

while read -r pid cmd; do
    [[ -z "$pid" ]] && continue

    pkg="?"
    color="$YELLOW"

    # Ядерные потоки
    if [[ "$cmd" == \[*\] ]]; then
        pkg="[kernel]"
        color="$BLUE"
    elif [[ -e /proc/$pid/exe ]]; then
        exe=$(readlink -f /proc/$pid/exe 2>/dev/null)
        if [[ -n "$exe" ]]; then
            if [[ -n "${cache[$exe]}" ]]; then
                pkg="${cache[$exe]}"
            else
                if res=$(dpkg -S "$exe" 2>/dev/null); then
                    pkg="${res%%:*}"
                else
                    pkg="?"
                fi
                cache[$exe]="$pkg"
            fi
            [[ "$pkg" != "?" ]] && color="$GREEN"
        fi
    fi

    printf "%-8s ${color}%-28s${NC} %s\n" "$pid" "$pkg" "$cmd"
done < <(ps -eo pid=,args= --no-headers)
