#!/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
	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
    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
		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 -en "\033[0m"
fi

exit 0
