#!/bin/bash

if [ $# -gt 0 ]; then
	ONLY=$1
fi

PROCS=""
JAILS=""
PJAILS=""
PJAILSt=""
JAILLIST=""

#ALLPS=`ps -o pid -A`
ALLPROCS=`ps aufx`

ALLPS=`echo "$ALLPROCS" |awk '{ print $2 }'`

for p in $ALLPS; do
	jail=`readlink /proc/$p/root`
	if [ "$jail" != "/" ]; then
		echo -n '.' >&2
		PROCS="$PROCS $p"
		PJAILS[$p]=$jail
		PJAILSt[$p]='chr'
		JAILS="$jail\n$JAILS"
	else
		nsjailx=`cat /proc/$p/mountinfo |awk '{print $4 "||" $5}' | grep '||/$' |grep -v '^/||/$'`
		if [ "$nsjailx" != "" ]; then
			echo -n ':' >&2
			nsjail=`echo "$nsjailx" |sed 's/||\///'`
			PROCS="$PROCS $p"
			PJAILS[$p]=$nsjail
			PJAILSt[$p]='cgrp'
			JAILS="$nsjail\n$JAILS"
		fi
	fi
done
echo >&2

#ALLPROCS=`ps afx`

if [ "x$ONLY" != "x" ]; then
	JAILLIST=$ONLY
else
	JAILLIST=`echo -e $JAILS |sort |uniq`
fi

function pslist()
{
echo -e 'PID\tCONTAINER\tUSER\t%CPU\t%MEM\tROOT\tCOMMAND'
echo
for jail in $JAILLIST; do
	for PROC in $PROCS; do
	    #pjail=`readlink /proc/$PROC/root`
	    pjail=${PJAILS[$PROC]}
	    if [ "$pjail" == "$jail" ]; then
#		echo "$ALLPROCS" | grep -e "^[^ ]*[ ]*$PROC" |sed -e "s#^#${jail} #"
		#echo "$ALLPROCS" | grep -e "^[ ]*$PROC" |awk '{ for (i=0; i<=4; i++) print $i " " "'${jail}'" "\t" $5 " " $6 $7 $8 $9 $10 }'
		#echo "$ALLPROCS" | grep -e "^[ ]*$PROC" |awk '{ for (i=1; i<=4; ++i) printf $i "\t" ; printf "'${jail}'" "\t"; for (i=5; i<=NF; ++i) printf $i " "; print "" }'
		#echo "$ALLPROCS" | grep -e "^[ ]*$PROC" |awk '{OFS="\t"}; { print $1,$3,$4,"'${jail}'",$5 " " $6 " " $7 " " $8 }'
		#echo "$ALLPROCS" | grep -e "^[^ ]*[ ]*$PROC" |awk '{OFS="\t"}; { print "'${jail}'",$2,$1,$3,$4,$10,$12 " " $13 " " $14 " " $15}'
		echo "$ALLPROCS" | grep -e "^[^ ]*[ ]*$PROC" |awk '{ printf "'${jail}'" "\t" "'${PJAILSt[$PROC]}'" "\t" $2 "\t" $1 "\t" $3 "\t" $4 "\t"; for (i=11; i<=NF; ++i) printf $i " "; print ""}'
	    fi
	done
	echo ""
done
}

pslist |column -e -t -s $'\t'
