#!/usr/bin/env bash
# ollie:parallel read
# args_json: {"type":"object","properties":{}}
# ollie:prompt
# ## process_list
#
# List background (detached) processes for this session.
#
# ```
# process_list()
# ```
#
# **Returns**: PID, command, start time, and status (running/exited) for each.
# ollie:end

set -euo pipefail

source "$(dirname "$0")/_lib/args.sh"

session="${OLLIE_SESSION_ID:?OLLIE_SESSION_ID not set}"

output=$(dbus-send --session --dest=org.ollie.SessionManager --type=method_call --print-reply \
  /org/ollie/SessionManager org.ollie.SessionManager.ListDetached \
  "string:$session" 2>&1)

entries=$(echo "$output" | grep 'string "' | sed 's/.*string "//;s/"$//' || true)

if [ -z "$entries" ]; then
    echo "No detached processes."
    exit 0
fi

printf '%-8s %-10s %-40s %s\n' 'PID' 'STATUS' 'COMMAND' 'STARTED'
printf '%-8s %-10s %-40s %s\n' '---' '------' '-------' '-------'
while IFS=$'\t' read -r pid cmd started status; do
    started_fmt=$(date -d "@$started" '+%H:%M:%S' 2>/dev/null || echo "$started")
    printf '%-8s %-10s %-40s %s\n' "$pid" "$status" "${cmd:0:40}" "$started_fmt"
done <<< "$entries"
