#!/bin/bash
# info: search for available commands
# options: ARG1 [ARG...]
#
# example: v-search-command web
#
# This function searches for available Hestia Control Panel commands
# and returns results based on the specified criteria.
# Originally developed for VestaCP by Federico Krum
# <https://github.com/FastDigitalOceanDroplets/VestaCP/blob/master/files/v-search-command>

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#
if [ $# -eq 0 ]; then
	echo "ERROR: No search arguments specified."
	echo "Usage: v-search-command ARG1 [ARG2] [ARG...]"
	exit 1
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

SearchResults=$(ls -a $BIN/ | sort)
TotalItems=$(ls -a $BIN/ | sort | wc -l)

for i; do
	SearchResults=$(echo $SearchResults | tr " " "\n" | grep $i)
	FoundItems=$(echo $SearchResults | tr " " "\n" | grep $i | wc -l)
done

if [ -z "$SearchResults" ]; then
	echo "No available commands were found matching the specified criteria."
	echo "There are a total of $TotalItems commands available."
else
	echo "Command Search Results"
	echo "================================="
	echo $SearchResults | tr " " "\n"
	echo "================================="
	echo "Found $FoundItems matching items in $TotalItems commands."
fi
exit
