#!/bin/bash
# This script was auto generated using the code-cleanup package http://forumubuntusoftware.info/viewtopic.php?f=23&t=9480
# Do a search and replace for ultimateedition.info followed by a search and replace bashdepends with the name of your program & delete this line.

# ==============================================================================
# title			:bashdepends
# description	:YOURDESCRIPTION
# author		:theemahn <theemahn@ultimateedition.info>
# date			:10/23/2013
# version		:1.0
# usage			:bashdepends --help
# manual		:man bashdepends
# notes			:See change-log below for further information.
# ==============================================================================
# Change-log:	1.7.1-8:First public Release
# 		1.7.2-1:Bump version to comply with release version.
# ==============================================================================

# Modify the below information to correlate with the software you are designing.
APPNAME="Bash Depends"
PROGNAME="bashdepends"
PROGRAMMER="TheeMahn"
BUILDDATE="10/01/2021"
VERSION="1.9.0"
DOMAIN="ultimateedition.info"
WEBSITE="http://${DOMAIN}/"
EMAIL="<${PROGRAMMER}@${DOMAIN}>"

source /usr/share/ultimate_edition/ultimate-common

CleanUP () {
	# self explanatory
	test -e /tmp/list.txt && rm /tmp/list.txt
	test -e /tmp/fulllist.txt && rm /tmp/fulllist.txt
	test -e /tmp/words.txt && rm /tmp/words.txt
	test -e /tmp/packages.txt && rm /tmp/packages.txt
	test -e /tmp/wip.txt && rm /tmp/wip.txt
	test -e /tmp/depends.txt && rm /tmp/depends.txt
	test -e $BFTP && rm $BFTP
}

GenerateList () {
	if test -s list.txt
	then
		echo -n "Depends: "
	else
		echo -e "${bldgrn}No external dependancies.${txtrst}"
		CleanUP
		exit 0
	fi
	NDEPENDS=$(cat list.txt | wc -l)
	cat /tmp/list.txt | while read FILE
	do
		PROCESS=$(($PROCESS + 1))
		DEPEND=$(echo $FILE | cut -d: -f1)
		DVERSION=$(echo $FILE | cut -d: -f2)
		# make sure if is not entered twice on the list for example the
		# commands "ar" and "as" are both part of binutils. We only want
		# it referenced once.
		if test -s fulllist.txt
		then
			ISTHERE=$(cat fulllist.txt | grep $DEPEND)
			if [[ $ISTHERE == "" ]]; then
				if [[ $NDEPENDS != $PROCESS ]]; then
					OUT=$OUT$DEPEND" (>="$DVERSION"), "
				else
					OUT=$OUT$DEPEND" (>="$DVERSION")"
				fi
			fi
		else
			if [[ $NDEPENDS != $PROCESS ]]; then
				OUT=$OUT$DEPEND" (>="$DVERSION"), "
			else
				OUT=$OUT$DEPEND" (>="$DVERSION")"
			fi
		fi
		# push list out to file bash gets dumb when it leaves a do done
		# loop and I do not feel like writing it to run in a sub shell.
		echo $OUT > fulllist.txt
	done
	cat fulllist.txt
	CleanUP
}

Chkdeps () {
	#dump header
	VersionDump
	# verify a parameter was passed
	if [[ $1 == "" ]];then
		echo -e "${bldred}Please specify a file.${txtrst}"
		exit 0
	fi

	# Filename in case user entered /bin/repomaster for example set to repomaster
	filename=${1##*/}

	# set bash file to process copy to temp
	cp $1 /tmp/
	BFTP="/tmp/"$filename

	# test for bash script existance
	test -s $BFTP || exit 0;
	echo -e "${bldgrn}Please wait this may take a while depending on the size of the script.${txtrst}"

	# roll to temp to begin processing.
	cd /tmp/

	# strip tabs
	sed -i 's/^[ \t]*//' $BFTP

	# strip comments
	sed -e 's/#.*$//' -e '/^$/d' $filename > wip.txt

	# strip echo a builtin
	sed -i '/echo .*/d' wip.txt

	# strip functions
	sed -i '/function .*/d' wip.txt
	sed -i '/}.*/d' wip.txt

	# strip Printf
	sed -i '/printf .*/d' wip.txt

	# strip braces
	cat wip.txt | tr -d "[]" > $filename

	# test for existance of temporary words list in case
	# this tool has been ran before.if so remove file.
	test -e /tmp/words.txt && rm /tmp/words.txt

	# grab commands used in bash file
	for word in $(cat "$BFTP")
	do
		[ -f '$word' -o -f /bin/$word ] && echo $word >> /tmp/words.txt &2>/dev/null
		[ -f '$word' -o -f /usr/bin/$word ] && echo $word >> /tmp/words.txt &2>/dev/null
	done

	cat $BFTP | grep '$(' | cut -d'(' -f2 | sed 's/ .*//g' >> /tmp/words.txt
	cat $BFTP | grep '`' | cut -d'`' -f2 | sed 's/ .*//g' >> /tmp/words.txt
	#strip empty lines
	sed -i '/^$/d' /tmp/words.txt
	#cat $filename | cut -d' ' -f1 >> words.txt
	#intiate array
	array_counter=0
	array_value=0

	#Declare array with all bash builtins
	declare -a Builtins=('alias' 'bg' 'bind' 'break' 'builtin' 'cd' 'command' 'compgen' 'complete' 'continue' 'declare' 'dirs' 'disown' 'echo' 'enable' 'eval' 'exec' 'exit' 'export' 'fc' 'fg' 'getopts' 'hash' 'help' 'history' 'jobs' 'kill' 'let' 'local' 'logout' 'popd' 'printf' 'pushd' 'pwd' 'read' 'readonly' 'return' 'set' 'shift' 'shopt' 'source' 'suspend' 'test' 'times' 'trap' 'type' 'typeset' 'ulimit' 'umask' 'unalias' 'unset' 'wait');

	#Strip references to bash builtin commands
	echo -e "${bldgrn}Stripping bash builtin commands.${txtrst}"
	for number in ${Builtins[@]}
	do
		sed -i "s/${Builtins[$array_counter]}//g" /tmp/words.txt
		array_counter=$(($array_counter + 1))
	done

	#scrap open brackets* from list
	sed -i 's/\[.*//g' /tmp/words.txt

	#scrap empty lines and a few builtins
	sed -i '/^$/d' /tmp/words.txt
	sed -i '/for .*/d' /tmp/words.txt
	sed -i '/from.*/d' /tmp/words.txt
	sed -i "/'/d" /tmp/words.txt

	#Start building dependancy list
	cat /tmp/words.txt | tr " " "\n" | sort | uniq >/tmp/depends.txt

	#Strip #'s
	sed -i '/sh/d' /tmp/depends.txt

	#Strip empty lines
	sed -i '/^$/d' /tmp/depends.txt

	#Initiate header & display results to end user
	echo -e "${bldgrn}Externally called commands:${txtrst}"

	# Check list existance no list no dependancies
	if test -s /tmp/depends.txt
		then
		cat /tmp/depends.txt
	else
		echo -e "${bldred}$1 has no external dependancies.${txtrst}"
		CleanUP
		exit 0
	fi

	#Initate header to display progress in scanning. Make it pretty ;)
	echo -e "${bldgrn}SCANNING FOR NON-ESSENTIAL / ESSENTIAL PACKAGE(S)..."
	printf '%-15s %-30s %-10s %s\n' \
	"COMMAND" "PACKAGE" "PRIORITY" "VERSION"

	#Punch out package database to reference later
	echo -e "${bldwht}________________________________________________________________________________${txtrst}"
	dpkg-query -Wf '${Package}:${Priority}:${Version}\n' | sort -b -k2,2 -k1,1 >/tmp/packages.txt
	test -e /tmp/list.txt && rm /tmp/list.txt

	#Set header for Control file
	cat /tmp/depends.txt | while read FILE
	do
		BINARY=$(which $FILE)
		if [[ $BINARY != "" ]]; then
			POSSIBLE=$(dpkg -S `which $BINARY` | cut -d":" -f1)
			PACKAGEPRIORITY=$(dpkg-query -s $POSSIBLE | grep "Priority:" | cut -d: -f2 | sed 's/ //g')
			PVERSION=$(dpkg-query -s $POSSIBLE | grep "Version:" | cut -d: -f2 | sed 's/ //g')
		else
			exit 0
		fi
		# I have not seen an unknown ever come up please report if you
		# see one and the package involved.
		case $PACKAGEPRIORITY in
			"standard")
			echo -e -n "${bldgrn}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";;
			"required")
			echo -e -n "${bldgrn}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";;
			"important")
			echo -e -n "${bldgrn}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";;
			"optional")
			echo -e -n "${bldred}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";
			echo "$POSSIBLE:$PVERSION" >> list.txt;;
			"extra")
			echo -e -n "${bldred}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";
			echo "$POSSIBLE:$PVERSION" >> list.txt;;
			*)
			echo -e -n "${bldblu}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "UNKNOWN" "$PVERSION";;
		esac
	done
	echo -e "${bldwht}Please add all red packages to your control file.${txtrst}"
	GenerateList
}

# Help system - I have re-wrote this section to work with code-cleanup.
Help () {

	if [[ "${2}" == "" ]]; then
		VersionDump
		PRAM="ALL"
	else
		if ! [[ "${3}" ]]; then
			VersionDump
			PRAM="${2}"
		else
			PRAM="${2}"
		fi
	fi

	case "${PRAM}" in
		ALL)
		Encapsulate "Usage: ${PROGNAME} -<-COMMAND> [OPTION]"
		FullBar
		Encapsulate "Mandatory arguments to long options are identical for short options."
		Encapsulate "  possible commands..."
		Encapsulate " "
		Encapsulate "  -d       --depends     find dependencies for <BASHSCRIPT>"
		Encapsulate "  -h       --help        this help message."
		Encapsulate "  -v       --version     dump version info and exit."
		Encapsulate " "
		FullBar
		Center "${PROGNAME} --help [COMMAND] for further information."
		FullBar;;

		# Version Help
		v|version)
		Encapsulate "Usage version;"
		FullBar
		Center "${PROGNAME} -v"
		FullBar
		Encapsulate "Displays ${PROGNAME}s version number and exits."
		FullBar;;

		# Help Help
		h|help|\?)
		Encapsulate "Usage Help [COMMAND]"
		FullBar
		Center "${PROGNAME} -h [COMMAND]"
		FullBar
		Encapsulate "Displays this message. For futher information ${PROGNAME} help [COMMAND]"
		Encapsulate "or refer to the manpages."
		Encapsulate " "
		Encapsulate "man ${PROGNAME}"
		Encapsulate " "
		Encapsulate "Example: ${PROGNAME} -h version"
		Encapsulate "Will display help about the command switch version"
		FullBar;;
		d|depends)
		Encapsulate "Usage Depends [COMMAND]"
		FullBar
		Center "${PROGNAME} -d [COMMAND]"
		FullBar
		Encapsulate "${PROGNAME} -d <BASHSCRIPT>"
		Encapsulate "Displays external dependencies on <BASHSCRIPT>.";;
	esac
	exit 0
}

TestBar () {
	CURRENTBRANCH=$(lsb_release -c | cut -d ":" -f2 | sed "s/ //g" | sed "s/	//g")
	if [[ "${CURRENTBRANCH}" ]]; then
		Encapsulate "Replacing ${CURRENTBRANCH} with impish sources to get the latest kernel."
		sudo sed -i "s/${CURRENTBRANCH}/impish/g" "/etc/apt/sources.list"
		Encapsulate "Running apt-get update..."
		sudo apt-get update >/dev/null & Spinner "Running apt-get update..."
		Encapsulate "Installing latest low-latency kernel..."
		sudo apt-get install linux-lowlatency linux-headers-lowlatency linux-image-lowlatency & Spinner "Installing latest low-latency kernel..."
		Encapsulate "Replacing impish sources back to ${CURRENTBRANCH}."
		sudo sed -i "s/impish/${CURRENTBRANCH}/g" "/etc/apt/sources.list"
		Encapsulate "Running apt-get update..."
		sudo apt-get update >/dev/null & Spinner "Running apt-get update..."
	else
		Error "Current Branch not detected, exiting."
		exit 1;
	fi
	Encapsulate "Testing Progress bar"
	i=0
	while [[ $i -ne 100 ]]
	do
        i=$(($i+1))
        ProgressBar "$i" "Testing Progress bar"
		sleep .1
	done
	Center "Testing Download Function"
	Download "http://os-builder.com/UETOYS/ultimate-edition-animated-1.0_all.deb"
}

# Command line pre-processor - this section of code is where your functions are called.
shopt -u nullglob
Timer "Start" "${APPNAME}"

case "${1}" in
      -d|--depends) Chkdeps "${2}"; exit 0;;
      -q|--quiet) VersionDump "$@"; CheckRoot "$@"; TestBar "$@"; exit 0;; # Hidden switch to increase program advancement
      -h|--help|-\?) Help "$@"; exit 0;; # TODO: Enhance this section.
      -v|--version) VersionDump "$@"; exit 0;;
      *) Help; exit 0;;
    esac


