#!/bin/bash

function bold
{
	echo $(tput bold)"$*"$(tput sgr0)
}


pomoc ()
{
	echo
	echo
	echo $(bold NAME)
	echo "	"$(basename $0)" - distro images creation"
	echo
	echo $(bold SYNOPSIS)
	echo "	"$(bold $(basename $0))" [OPTION] ... [distro image name | all]"
	echo
	echo $(bold DESCRIPTION)
	echo "	""Create distro images ready to boot with PXE method."
	echo
	echo "		"$(bold '-c, --create')
	echo "			""create distro image tgz contener described in the next argument;"
	echo "			""as the second argument could be used '"$(bold all)"' argument;"
	echo "			"$(bold all)" argument force all existing images creation."
	echo
	echo "		"$(bold '-l, --list')
	echo "			""list distro images exiting on the host file system and ready to boot with PXE method."
	echo
	echo "		"$(bold '-a, --author')
	echo "			""print author name."
	echo
	echo "		"$(bold '-v, --version')
	echo "			""print script version."
	echo
	echo "		"$(bold '-d, --date')
	echo "			""print script creation date."
	echo
	echo "		"$(bold '-h, --help')
	echo "			""print this help"
	echo
	echo $(bold AUTHOR)
	echo "		""Written by ""$Author"
	echo
	echo $(bold CREATIN DATE)
	echo "		""0$CreationDate"
	echo
	echo $(bold VERSION)
	echo "		""$Version"
	echo
}

list_avaiable_distroimages ()
{
	while [ "$#" != 0 ]; do
		zm="$1"
		zm="${zm::-1}"
		zm="$(echo $zm | awk -F / '{print $NF}')"
		# echo ${zm::-1}
		echo $zm
		shift
	done

}

creation ()
{
	while [ "$#" != 0 ]; do
		var1=$(echo "$1" | awk -F / '{print $NF}')

		if [ ! -d "$DistroImagesPath"/"$var1" ] || [ ! -d "$DistroImagesPath2"/"$var1" ]; then
			echo "$var1"" - ""There is now distro image or is not complete. Ignoring."
		else
			NAPIS="Contener creation ""$var1"
			echo -en "      ""$NAPIS"
				tar czf "$1".tgz \
					"$DistroImagesPath"/"$1" \
					"$DistroImagesPath2"/"$1" &>> /dev/null
			echo-kropki $ALIGNMENT "                  ""$NAPIS" DONE zielony bold
		fi

		shift

	done
}

##################################################################################

DistroImagesPath="/opt/distroimages"
DistroImagesPath2="/tftpboot/distroimages"
Author="Radek Bursztynowski"
CreationDate="02.08.2023"
Version="1.0"
Lib=/opt/bash.libs
ALIGNMENT=78

. "$Lib"/kolory
. "$Lib"/bash.lib.01
. "$Lib"/yad.lib.01

if [ "$#" = 0 ]; then
	pomoc
fi

case "$1" in
	-c | --create)
		shift

		if [ "$1" = "all" ]; then
			creation $(list_avaiable_distroimages $(ls -d "$DistroImagesPath"/*/))
		else
			creation $@
		fi
	;;

	-l | --list)
		list_avaiable_distroimages $(ls -d "$DistroImagesPath"/*/)
	;;

	-a | --author)
		"$Author"
	;;

	-v | --version)
		"$Version"
	;;

	-d | --date)
		"$CreationDate"
	;;

	-h | --help)
		pomoc
	;;

	*)
		echo "Wrong parameter. Use "$(basename $0)" --help"
	;;
esac



