#!/bin/bash
#
# Copyright (c) Authors: https://www.armbian.com/authors
#
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.

# DO NOT EDIT THIS FILE but add config options to /etc/default/armbian-motd
# any changes will be lost on board support package update

THIS_SCRIPT="commands"
MOTD_DISABLE=""

[[ -f /etc/default/armbian-motd ]] && . /etc/default/armbian-motd

# read upgrade count to show upgrade command
[[ -f /var/cache/apt/archives/updates.number ]] && . /var/cache/apt/archives/updates.number

for f in $MOTD_DISABLE; do
	[[ $f == $THIS_SCRIPT ]] && exit 0
done

# text, sudo / without, command, condition
# condition can be fairly complex
list=(
    "Configuration","","armbian-config","true"
    "Upgrade","","armbian-upgrade","[[ \"${NUM_UPDATES}\" -gt 0 ]]"
    "Monitoring","","htop","true"
)

# verify if command exits on the system
cmd_count=0
name_len=0
output=()
for l in "${list[@]}"
do
	name=$(echo $l | cut -d"," -f1)
	sudo=$(echo $l | cut -d"," -f2)
	command=$(echo $l | cut -d"," -f3)
	condition=$(echo $l | cut -d"," -f4)
	if eval $condition 2> /dev/null && command -v $command &> /dev/null
	then
		# seek for maximum description lenght
		if [ ${#name} -ge $name_len ]; then
			name_len=${#name}
		fi
		cmd_count=$(( cmd_count +1 ))
		output+=("${name},${sudo},${command}")
	fi
done

# show list for existing command only
if [[ "${cmd_count}" -gt 0 ]]; then
	printf "\e[0;90m Commands: \x1B[0m\n" #; printf '%.s─' $(seq 1 39); echo -e "\x1B[0m"
	echo ""
	for l in "${output[@]}"
	do
		name=$(echo $l | cut -d"," -f1)
		sudo=$(echo $l | cut -d"," -f2)
		command=$(echo $l | cut -d"," -f3)
		printf " \e[1;33m%-${name_len}s\e[0m %-0s: $sudo$command\n" "$name"
	done
	echo -e "\033[0m"
fi

exit 0
