#!/bin/sh

deviceStackName=devicestack
#deviceStackPID=$(cat /var/run/$deviceStackName.pid)

# Find and show child processes of a given pid
# $1 - PID of the process which childs shall be shown
# $2 - Prefix for the output (Should be omited at the initial call)
showChilds() (
  pid=$1
  prefix=$2

  files=$(ls -1 -d /proc/[1-9]*)
  for file in $files
  do
    grep -q -e "PPid.*$pid" $file/status 2>/dev/null
    if [ $? -eq 0 ]
    then
	childPID=$(basename $file)
	childName=$(grep Name /proc/$childPID/status | awk '{print $2}')
	childCmdline=$(cat /proc/$childPID/cmdline | xargs -0 echo)
	echo "$prefix" $childPID $childName $childCmdline
        showChilds $childPID "$prefix  "
    fi
  done
)

echo Searching for devicestack processes
files=$(ls -1 -d /proc/[1-9]*)
for file in $files
do
  grep -q "devicestack" $file/cmdline 2>/dev/null
  if [ $? -eq 0 ]
  then
      deviceStackPID=$(basename $file)
      echo PID found: $deviceStackPID
  fi
done
echo

showPID=true
showSO=false
showChilds=false


# Command line parameter
if [ $# -eq 0 ]
then
  showPID=true
  showSO=true
  showChilds=true
else
  while [ $# -ne 0 ]
  do
    parameter=$1
    case $parameter in
    --forcepid)
      deviceStackPID=$2
      shift
      ;;
    --all)
      showPID=true
      showSO=true
      ;;
    --pid)
      showPID=true
      ;;
    --so)
      showSO=true
      ;;
    --childs)
      showChilds=true
      ;;
    *)
      echo "$parameter is not supported." 1>&2
      exit 1
    esac
    shift
  done
fi

# Is the DeviceStack running?
if [ -z "$deviceStackPID" -o ! -d /proc/$deviceStackPID ]
then
  echo $deviceStackName is not running.
  exit
fi

# Show the PID
if [ $showPID = true ]
then
  echo PID:
  echo $deviceStackPID
  echo
fi

# Show dynamically linked libraries
if [ $showSO = true ]
then
  echo Dynamically loaded libraries:
  cat /proc/$deviceStackPID/maps | awk '{print $6}' | grep '\.so' | sort | uniq
  echo
fi

# Show child processes
if [ $showChilds = true ]
then
  echo Child processes:
  showChilds $deviceStackPID
  echo
fi
