#!/bin/sh
# List PM2 apps for an already-running daemon. Root-owned.
# Called as: sudo -n -u <pm2-uid> -H /usr/lib/docker-log-viewer/pm2-jlist /path/to/.pm2
# The only pm2 command this script runs is `jlist`. It does not start a daemon.
set -eu

home=${1:-}
case "$home" in
	/*) ;;
	*)
		echo "PM2 home must be an absolute path" >&2
		exit 2
		;;
esac
case "$home" in
	*..*)
		echo "PM2 home must not contain .." >&2
		exit 2
		;;
esac
if [ ! -d "$home" ]; then
	echo "PM2 home not found" >&2
	exit 1
fi

alive=0
if [ -f "$home/pm2.pid" ]; then
	pid=$(tr -cd '0-9' < "$home/pm2.pid" | head -c 12)
	if [ -n "$pid" ] && [ -d "/proc/$pid" ]; then
		alive=1
	fi
fi
if [ "$alive" -ne 1 ]; then
	for cmd in /proc/[1-9]*/cmdline; do
		[ -r "$cmd" ] || continue
		text=$(tr '\0' ' ' < "$cmd" 2>/dev/null || true)
		case "$text" in
			*"God Daemon ($home)"*)
				alive=1
				break
				;;
		esac
	done
fi
if [ "$alive" -ne 1 ]; then
	echo "PM2 daemon is not running in $home" >&2
	exit 1
fi

pm2bin=""
for c in /usr/local/bin/pm2 /usr/bin/pm2; do
	if [ -x "$c" ]; then
		pm2bin=$c
		break
	fi
done
if [ -z "$pm2bin" ] && [ -n "${HOME:-}" ]; then
	for c in "$HOME"/.nvm/versions/node/*/bin/pm2 "$HOME"/.local/bin/pm2; do
		if [ -x "$c" ]; then
			pm2bin=$c
			break
		fi
	done
fi
if [ -z "$pm2bin" ]; then
	echo "pm2 binary not found for this user" >&2
	exit 1
fi

# nvm installs pm2 as a #!/usr/bin/env node script; sudo's secure_path has no node.
PATH="$(dirname "$pm2bin"):${PATH:-/usr/bin:/bin}"
export PATH
export PM2_HOME="$home"
exec "$pm2bin" jlist
