#!/bin/bash
#
# Collect debug information of number of processes/threads
# running on the system
#
#  Copyright (c) 2021 by cisco Systems, Inc.
#  All rights reserved.
#

opt=$1
state=$2

DEBUG_DIR="/var/log/debug_proc_cnt"

if [ ! -d $DEBUG_DIR ]
then
    mkdir -p $DEBUG_DIR
fi

debug_proc="$DEBUG_DIR/debug_process.`date +"%Y-%m-%d-%H_%M_%S"`.log"
debug_thread="$DEBUG_DIR/debug_thread.`date +"%Y-%m-%d-%H_%M_%S"`.log"

if [[ "$opt" == "proc" ]]
then
    echo -n "State : " >> $debug_proc
    echo $state >> $debug_proc
    echo -n "Total number of processes : " >> $debug_proc
    ps -ef | wc -l >> $debug_proc
    ps -ef >> $debug_proc
fi

if [[ "$opt" == "thread" ]]
then
    echo -n "State : " >> $debug_thread
    echo $state >> $debug_thread
    echo -n "Total number of processes : " >> $debug_thread
    ps axms | wc -l >> $debug_thread
    ps axms >> $debug_thread
fi

debug_files=($(ls -tr $DEBUG_DIR))

i=${#debug_files[*]}

if [ $i -ge 19 ]
then
    # Keep the 10 oldest and 8 newest
    k=$(($i-8))
    j=10
    while [ $j -lt $k ]
    do
        rm -f $DEBUG_DIR/${debug_files[$j]} 2>/dev/null
        j=$(($j+1))
    done
fi

