#!/bin/bash
# panel-ps procs   — all processes with CURRENT cpu/mem (top, second sample), tab separated:
#                    pid user state cpu% mem% rss_kb elapsed command
# panel-ps mysql   — running MySQL queries (not sleeping), tab separated: id user db time state info
# panel-ps kill <pid>  — stop a process of the hosting user (never root/system processes)
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
if [ "${1:-}" = on ]; then   # the same on a connected server
  srv="${2:-}"; ip=$(node_ip "$srv") || die "unknown server: $srv"; shift 2
  exec timeout 30 ssh "${NODE_SSH_OPTS[@]}" "root@$ip" "/opt/panel/bin/panel-ps $(printf '%q ' "$@")"
fi
case "${1:-}" in
  procs)
    top -b -c -n 2 -d 0.5 -o %CPU -w 512 | awk '
      /^ *PID /{blk++; next}
      blk==2 && NF>=12 { cmd=$12; for(i=13;i<=NF;i++) cmd=cmd" "$i; print $1"\t"$2"\t"$8"\t"$9"\t"$10"\t"$6"\t"$11"\t"cmd }' | head -400
    ;;
  mysql)
    mysql -N -B -e "select id, user, coalesce(db,''), time, coalesce(state,''), left(replace(replace(coalesce(info,''),'\n',' '),'\t',' '),300)
                    from information_schema.processlist where command <> 'Sleep' and id <> connection_id() order by time desc limit 200" 2>/dev/null || true
    ;;
  kill)
    pid="${2:-}"; [[ "$pid" =~ ^[0-9]+$ ]] || die "pid?"
    owner=$(ps -o user= -p "$pid" 2>/dev/null | tr -d ' ') || true
    [ -n "$owner" ] || die "process $pid not found"
    [ "$owner" = "$PANEL_USER" ] || die "only processes of $PANEL_USER can be stopped here (this one belongs to $owner)"
    kill "$pid" && echo "stopped process $pid ($(ps -o comm= -p "$pid" 2>/dev/null || echo ended))"
    ;;
  *) die "usage: panel-ps procs | mysql | kill <pid>" ;;
esac
