#!/bin/bash
#

function startTimeOfPid {
    startTime=$(awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next } END { print strftime("%Y-%m-%dT%H:%M:%SZ", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/${pid}/stat)
    let startTimeEpoch=$(awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next } END { print strftime("%s", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/${pid}/stat)
    startTimeHuman=$(awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next } END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/${pid}/stat)
}
 
pgrep -laf "just check if -laf is available" >/dev/null 2>/dev/null;
rc=$?;
if [ "$rc" == "2" ]; then
        # -laf is not available
    pgreppar="-lf"
else
    pgreppar="-laf"
fi

separator=""
 
OIFS="$IFS"
IFS=$'\n'
echo -n "["
for process in $(pgrep ${pgreppar} ".*\.prc" | grep -v pgrep | grep -v -E "isdn.prc|readchannel.prc"); do
    echo $separator

    pid=$(echo $process | cut -d " " -f 1)
    taskName=$(echo $process | cut -d " " -f 2 | sed -e "s#.*/\(.*\)#\1#")

    startTimeOfPid

    calledPartyNumber=$(echo $process | sed -e "s/.*\--calledPartyNumber=\([^ ]*\) .*/\1/")

    callingPartyNumber=$(echo $process | sed -e "s/.*\--callingPartyNumber=\([^ ]*\) .*/\1/")

    let nowEpoch=$(date +%s)
    let runTimeEpoch=$((nowEpoch - startTimeEpoch))

    runTime=$(printf '%dh:%dm:%ds\n' $(($runTimeEpoch/3600)) $(($runTimeEpoch%3600/60)) $(($runTimeEpoch%60)))

    type="Phone"
    if [ $taskName == "fax.prc" ] ; then type="Fax";
    elif [ $taskName == "faxt38.prc" ] ; then type="Fax";
    elif [ $taskName == "voice.prc" ] ; then type="IVR";
    fi

    echo "  {"
    echo "    \"pid\": $pid,"
    echo "    \"taskName\": \"$taskName\","
    echo "    \"type\": \"$type\","
    echo "    \"calledPartyNumber\": \"$calledPartyNumber\","
    echo "    \"callingPartyNumber\": \"$callingPartyNumber\","
    echo "    \"startTimeHuman\": \"$startTimeHuman\","
    echo "    \"startTime\": \"$startTime\","
    echo "    \"startTimeEpoch\": $startTimeEpoch",
    echo "    \"runTime\": \"$runTime\","
    echo "    \"runTimeEpoch\": $runTimeEpoch"
    echo -n "  }"

    separator=","
done
echo ""
echo "]"
IFS="$OIFS"


