#!/bin/bash

USE_VERSIONS=false
USE_JSON=false
DEBUG=false


__print_usage() {
	echo ""
	echo "voxl-inspect-services"
	echo ""
	echo "Lists the status of all modalai services"
	echo ""
	echo "Options:"
	echo -e "\t-h|--help     : Show this help message"
	echo -e "\t-d|--debug    : debug mode"
	echo -e "\t-v|--version  : Show versions as well (takes longer to run)"
	echo -e "\t-j|--json	 : Output in Json Format"
	echo ""
}

for arg in "$@" ; do
	case $arg in

		--version|-v)
			USE_VERSIONS=true
		;;

		--help|-h)
			__print_usage
			exit 0
		;;

		--debug|-d)
			DEBUG=true
		;;

		--json|-j)
			USE_JSON=true
		;;

		*)
			echo "unknown argument $arg"
			__print_usage
			exit 1
	esac
done


if [ "$USE_JSON" == false ]; then
	echo "Scanning services..."
fi

VALID_SERVICES='voxl|modal|docker|px4'

# Get Array of available services
SERVICES=( $( ls /etc/systemd/system/ | egrep ${VALID_SERVICES} | sed s/.service//g ) )

MAX_LEN=0

VERSIONS=()
ENABLEDS=()
RUNNINGS=()
CPUS=()


## let top run for two prints (-n 2) since the first one will not have collected data yet
## shorten measurement time from 3s to 0.5s (-s 0.5)
## and trim off the first half of the output
TOP_OUTPUT=$(top -b -n 2 -d 0.5 | egrep "${VALID_SERVICES}|CPU" | awk 'NR==1{c=0} /PID/ {c++} c>=2{print}')
if $DEBUG ; then
	echo $TOP_OUTPUT
fi
TARGET="%CPU"
TOP_HEADER=$(echo "${TOP_OUTPUT}" | grep "${TARGET}" )
REST=${TOP_HEADER#*$TARGET}
TARGET_POS=$(( ${#TOP_HEADER} - ${#REST} - ${#TARGET} ))




for i in $( seq 0 $((${#SERVICES[@]}-1)) ) ; do

	if $DEBUG; then
		echo "CHECKING SERVICE: ${SERVICES[i]}"
	fi

	if [ ${#SERVICES[i]} -gt $MAX_LEN ] ; then
		MAX_LEN=${#SERVICES[i]}
	fi

	if [ "$USE_VERSIONS" = true ] ; then
		if [ -f /usr/bin/dpkg ]; then
			VERSIONS+=($(dpkg-query --showformat='${Version}' --show "$(dpkg --search /etc/systemd/system/${SERVICES[i]}.service | cut -d ":" -f 1)" | cut -d "-" -f 1))
		else
			VERSIONS+=($(opkg search /etc/systemd/system/${SERVICES[i]}.service | sed 's/^.*- //'))
		fi
	fi

	if [[ "$(systemctl is-enabled ${SERVICES[i]})" == "enabled" ]]; then
		if [ "$USE_JSON" == true ]; then
			ENABLEDS+=("Enabled")
		else 
			ENABLEDS+=("${CLR_GRN} Enabled ${RESET_ALL}")
		fi
	else
		if [ "$USE_JSON" == true ]; then
		ENABLEDS+=("Disabled")
		else
			ENABLEDS+=("${CLR_RED}Disabled ${RESET_ALL}")
		fi
	fi
	if [[ "$(systemctl is-active ${SERVICES[i]})" == "active" ]]; then


		## voxl-px4 is unique
		if [ ${SERVICES[i]} == "voxl-px4" ]; then
			PID=$(pidof px4)
		else
			# fetch PID from systemd
			PID=$(systemctl show -p MainPID ${SERVICES[i]})
			PID=${PID:8} # trim the "mainPID=" text from the beginning
		fi

		## an "active" service with pid = 0 means it successfully completed
		if [ ${PID} == "0" ]; then
			if [ "$USE_JSON" == true ]; then
				RUNNINGS+=("Completed")
				CPUS+=("Null")
			else 
				RUNNINGS+=("${CLR_GRN} Completed ${RESET_ALL}")
				CPUS+=(" ")
			fi
		else
			## if we got here, the service is running
			if [ "$USE_JSON" == true ]; then
				RUNNINGS+=("Running")
			else
				RUNNINGS+=("${CLR_GRN}  Running  ${RESET_ALL}")
			fi

			# voxl-px4 doesn't match the binary name (px4) so grep by PID instead
			if [ ${SERVICES[i]} == "voxl-px4" ]; then
				if $DEBUG; then
					echo "grepping top for" ${PID}
				fi
				TMP_CPU=$( echo "${TOP_OUTPUT}" | grep -m 1 ${PID} | cut -c "${TARGET_POS}-" | awk '{ print $1 }' )
			else
				if $DEBUG; then
					echo "grepping top for" ${SERVICES[i]:0:12}
				fi
				TMP_CPU=$( echo "${TOP_OUTPUT}" | grep -m 1 ${SERVICES[i]:0:12} | cut -c "${TARGET_POS}-" | awk '{ print $1 }' )
			fi

			if $DEBUG; then
				echo "TMP_CPU: " $TMP_CPU
			fi

			if [ "$USE_JSON" == true ]; then
				CPUS+=($TMP_CPU)
			elif [[ -n "$TMP_CPU" ]]; then
				# format it nicely as a colored percentage
				INT_CPU=${TMP_CPU%.*}
				if [[ "$INT_CPU" -ge "50" ]] ; then
					TMP_CLR=$CLR_RED
				elif [[ "$INT_CPU" -ge "20" ]] ; then
					TMP_CLR=$CLR_YLW
				else
					TMP_CLR=$CLR_GRN
				fi
				CPUS+=( "${TMP_CLR}  $( printf "%5.1f%q" $TMP_CPU "%" )${RESET_ALL}" )
			else
				CPUS+=(" ")  # Add placeholder when CPU data unavailable
			fi
		fi

	else
		if [ "$USE_JSON" == true ]; then
			RUNNINGS+=("Not Running")
			CPUS+=("Null")
		else
			RUNNINGS+=("${CLR_RED}Not Running${RESET_ALL}")
			CPUS+=(" ")
		fi

	fi
done

if [ "$USE_JSON" = true ]; then
	echo -n  "{"
	echo -n "\"Services\": {"
	for i in $(seq 0 $((${#SERVICES[@]}-1))); do
		echo -n " \"${SERVICES[i]}\": {"
		if [ "$USE_VERSIONS" = true ] ; then
			echo -n "\"Version\": \"${VERSIONS[i]}\","
		fi
		echo -n "\"Enabled\": \"${ENABLEDS[i]}\", "
		echo -n "\"Running\": \"${RUNNINGS[i]}\", "
		if [ "${CPUS[i]}" == "Null" ]; then
			echo -n "\"Cpu_usage\": null"
		else
			echo -n "\"Cpu_usage\": \"${CPUS[i]}\""
		fi
		echo -n "}"
		if [ $i -lt $((${#SERVICES[@]}-1)) ]; then
			echo -n ","
		fi
	done
	echo -n "}"
	echo -n "}"
else 

	MAX_LEN=$(($MAX_LEN+1))

	# Longest Service Name
	#echo "$MAX_LEN"

	echo ""
	echo -ne "${SET_BOLD}"

	printf " %-*s |" $MAX_LEN "Service Name"

	if [ "$USE_VERSIONS" = true ] ; then
		printf "  Version  |"
	fi
	echo "  Enabled  |   Running   |  CPU Usage"

	for i in $( seq 1 $MAX_LEN ) ; do
		echo -ne "─"
	done
	echo -n "───────────────────────────────────────────"
	if [ "$USE_VERSIONS" = true ] ; then
		echo -n "────────────"
	fi

	echo ""
	echo -ne "${RESET_ALL}"

	for i in $( seq 0 $((${#SERVICES[@]}-1)) ) ; do

		printf " %-*s |" $MAX_LEN ${SERVICES[i]}

		if [ "$USE_VERSIONS" = true ] ; then
			printf " %8s  |" ${VERSIONS[i]}
		fi
			
		echo -ne " ${ENABLEDS[i]} |"          
		echo -ne " ${RUNNINGS[i]} |"  
		echo -ne " ${CPUS[i]}"
		echo ""    
			
	done

fi
