#!/bin/bash

#
# Name:         rsb-ps-top
# Version:      1.0.0
#
# (c) 2024, Rapidseedbox, alexey@rapidseedbox.com
#

set -o pipefail

export LANG=en_US
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

SC_NAME="$( basename "${0}" )"
SC_VER="$( grep -m 1 -E '^#\s*Version:\s+' "${0}" | awk '{print $NF}' )"

_rc=0
for _cmd in \
    "pgrep" \
; do
    if ! command -v "${_cmd}" > /dev/null 2>&1 ; then
        >&2 echo "${_cmd}: command not found!"
        (( _rc ++ ))
    fi
done
if [ "${_rc}" != "0" ] ; then
    >&2 echo "Cannot continue..."
    exit 1
fi


_usage() {
    cat <<-EOF

	${SC_NAME} ${SC_VER}

	Show top processes by count

	Usage:
	------------
	    ${SC_NAME} [-h] [-n NUM]

	    -h       - Display this help message
	    -n NUM   - Show NUM top processes (default: 10)

	EOF
}

# Parse command line
PARSE_ERR=0
NUM="10"
while getopts ":n:h" params; do
    case "${params}" in
      h)
          _usage ; exit 0
          ;;
      n)
          if [[ ${OPTARG} = -* ]] ; then
              [ -n "${ERR_MSG}" ] && ERR_MSG="${ERR_MSG}; "
              ERR_MSG="${ERR_MSG}Option -${params} requires an argument"
              PARSE_ERR=1
              continue
          fi
          NUM="${OPTARG}"
          ;;
      \?) 
          >&2 echo "Invalid option: -${OPTARG}" >&2
          PARSE_ERR=1
          ;;
    esac
done
if [ "${PARSE_ERR}" != "0" ] ; then
    _usage ; exit 2
fi
shift "$(( OPTIND - 1 ))"


pgrep -l -f '.*' \
    | sort -k 2 \
    | awk '{print $2}' \
    | uniq -c \
    | sort -rn -k 1 \
    | head -${NUM}

_rc=$?

exit ${_rc}
