#!/usr/bin/env bash
# ollie:parallel read
# description: List background (detached) processes for this session. Shows PID, command, start time, and status.
# Args: (none)

set -euo pipefail

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)

# Parse the D-Bus array response
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
    # Convert unix timestamp to human-readable
    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"
