#!/bin/sh

deviceStackName=devicestack

# 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)
      printf "%s %s %s %s\\n" "$prefix" "$childPID" "$childName" "$childCmdline"
      showChilds $childPID "$prefix  "
    fi
  done
)

printf "Searching for devicestack processes\\n"
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)
      printf "PID found: %s\\n" "$deviceStackPID"
  fi
done
printf "\\n"

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
      ;;
    *)
      printf "%s is not supported.\\n" "$parameter" 1>&2
      exit 1
    esac
    shift
  done
fi

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

# Show the PID
if [ $showPID = true ]
then
  printf "PID:\\n"
  printf "%s\\n\\n" "$deviceStackPID"
fi

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

# Show child processes
if [ $showChilds = true ]
then
  printf "Child processes:\\n"
  showChilds $deviceStackPID
  printf "\\n"
fi
