#!/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=""

safe_source() { [[ -f "$1" ]] && . "$1"; }

# Optional overrides
safe_source /etc/default/armbian-motd
for f in ${MOTD_DISABLE}; do
	[[ "${f}" == "${THIS_SCRIPT}" ]] && exit 0
done

_motd_spacer() {
  local tag="${1:-after-header}"
  local dir="/run/armbian-motd"; local stamp="$dir/.${tag}.printed"
  mkdir -p "$dir" 2>/dev/null
  [[ -e "$stamp" ]] || { echo ""; : > "$stamp"; }
}

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

# 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
	IFS=',' read -r name sudo command condition <<< "$l"
	if [[ "${condition}" == "true" ]] || eval "${condition}" 2> /dev/null; then
		if command -v "${command}" &> /dev/null; then
			# seek for maximum description length
			if [[ ${#name} -ge ${name_len} ]]; then
				name_len=${#name}
			fi
			cmd_count=$(( cmd_count + 1 ))
			output+=("${name},${sudo},${command}")
		fi
	fi
done

# show list for existing command only
if [[ "${cmd_count}" -gt 0 ]]; then
    echo ""   # ensure we start on a fresh line
	printf "\e[0;90m Commands: \x1B[0m\n" #; printf '%.s─' $(seq 1 39); echo -e "\x1B[0m"
	echo ""
	for l in "${output[@]}"
	do
		IFS=',' read -r name _ command <<< "$l"
		printf " \e[1;33m%-${name_len}s\e[0m: \e[0;92m%s\e[0m\n" "$name" "${command}"
	done
	echo -en "\033[0m"
fi

exit 0
