#!/bin/sh
# [Gedit Tool]
# Name=New Bash Script
# Applicability=all
# Input=document
# Output=replace-document
# Save-files=nothing

WEBSITE="ultimateedition.info"
IUSER=${SUDO_USER:-$USER}
IHOME="/home/${IUSER}"
MUSER=`users | awk '{print $1}'`
TUSER=$(grep -i "${USER}" "/etc/passwd" | cut -d ":" -f5 | sed "s/,//g")

echo "#!/bin/bash"
echo "# This script was auto generated using the code-cleanup package http://forumubuntusoftware.info/viewtopic.php?f=23&t=9480"
echo "# Do a search and replace for ultimateedition.info followed by a search and replace REPLACEME with the name of your program & delete this line."
echo "
# ==============================================================================
# title			:REPLACEME
# description	:YOURDESCRIPTION
# author		:$USER <$USER@$WEBSITE>
# date			:`date +"%m/%d/%Y"`
# version		:1.0
# usage			:REPLACEME --help
# manual		:man REPLACEME
# notes			:See change-log below for further information.
# ==============================================================================
# Change-log: 1.0: unreleased
# ==============================================================================

# Modify the below information to correlate with the software you are designing."
echo 'APPNAME="Application-Name"'
echo 'PROGNAME="REPLACEME"'
echo 'PROGRAMMER="'${TUSER}'"'
echo 'BUILDDATE="'`date +"%m/%d/%Y"`'"'
echo 'VERSION="'1.0'"'
echo 'DOMAIN="'${WEBSITE}'"'
echo 'WEBSITE="http://${DOMAIN}/"'
echo 'EMAIL="<${PROGRAMMER}@${DOMAIN}>"'
echo '

# ==============================================================================
# Need to get Personal? Scrap this section if you do not need to know the user.
# Pull info we may / or may not use to compare against later
IUSER=${SUDO_USER:-$USER}
IHOME="/home/${IUSER}"

# ==============================================================================
# Terminal Detection & color
case "${TERM}" in
  "dumb");;
  *)
	COLUMNZ=$(tput cols)
	txtred=$(tput setaf 1)
	txtgrn=$(tput setaf 2)
	bldblu=$(tput setaf 4)
	txtrst="\e[0m"	# Text Reset
	BRIGHT=$(tput bold);;
esac
# Added in 1.0.7 - Taking a stab at calculating disk sizes smartly up to Yottabyte
# Could easily roll up to a Geopbyte.
# · 1 Bit = Binary Digit
# · 8 Bits = 1 Byte
# · 1024 Bytes = 1 Kilobyte
# · 1024 Kilobytes = 1 Megabyte
# · 1024 Megabytes = 1 Gigabyte
# · 1024 Gigabytes = 1 Terabyte
# · 1024 Terabytes = 1 Petabyte
# · 1024 Petabytes = 1 Exabyte
# · 1024 Exabytes = 1 Zettabyte
# · 1024 Zettabytes = 1 Yottabyte
# · 1024 Yottabytes = 1 Brontobyte
# · 1024 Brontobytes = 1 Geopbyte

# See additional code in function DumpArray to see how I did so using the array
# defined below.
declare -a DISKSIZES=("KB" "MB" "GB" "TB" "PB" "EB" "ZB" "YB")
#declare -i KBS

# Check to see if notify is installed & if sound is supported.
NOTIFY=$(type -p notify-send)
SOUND=$(type -p canberra-gtk-play)

# ==============================================================================
# Declare integers to span eye-candy routine, no eyecandy?
# Scrap this entire section.
declare -i RR
RR=0
declare -i TT
TT=0
declare -i CALC
CALC=0

# Logging?
# Logging output - Currently un-implemented
# exec 1> /var/log/REPLACEME.log
# exec 1>> /var/log/REPLACEME.log 2>&1
# Multiple log files?
declare -a LOG_FILE=( "/var/log/REPLACEME.log" );
# Single Log
# LOG_FILE="/var/log/REPLACEME.log"
# exec 1 | tee ${LOG_FILE}
# exec 2 | tee ${LOG_FILE}

# Commonly used info
DATECURRENT=$(date +"%Y%m%d")
DEBUG=$(echo "$*" | grep -i "debug")

# Get Directory executed in.
CURRENT="${PWD}"'

echo '
# T R A P  EVENTS
finish () {
	if [[ "${DEBUG}" ]]; then
		echo "EUID: ${EUID} | USER: ${USER} | IUSER: ${IUSER} | ROOT: ${TRUEROOT} EXIT CODE: $?"
	fi
	Timer "Stop"
	FullBar
}

# trap ctrl-c and call ctrl_c()
ctrl_c () {
		Encapsulate "** Trapped CTRL-C, exiting."
		FullBar
		Timer "Stop"
		FullBar
		exit 1;
}

trap ctrl_c INT
trap finish EXIT

# Begin programming here.


'

echo '# Common Functions to make programming easier, dont need them delete them.
# Calculate percentage usage: x=$(Percent 2 3 2) ; echo $x # gives 66.66
# The first 2 / 3, the last is the scale ie 2 decimal places
Percent () {
	echo "scale = ${3}; ${1} * 100 / ${2}" | bc
}

FileSize () {
	FTP="${1}"
	if [[ -f "${FTP}" ]]; then
		TOTALSIZE=$(stat -c%s "${FTP}")
		FORMATTED=$(echo "${TOTALSIZE}" | \
sed -r "
  :L
  s=([0-9]+)([0-9]{3})=\1,\2=
  t L")
		KBS=$(echo "scale=2;${TOTALSIZE%/*}/1024"|bc)
		SIZE="${TOTALSIZE}"
		for XX in "${DISKSIZES[@]}"
		do
			SIZE=$(echo "scale=2;${SIZE%/*}/1024"|bc)
			# Dump the decimal just to see if we have hit the 1024 or less mark.
			KBS=$(echo "$SIZE" | cut -d . -f1)
			# Debugging:
			# echo "TESTINGSIZE: $KBS $XX"
			if [[ "$KBS" -lt 1024 && "$KBS" -gt 1 ]]; then
				TRUESIZE="${KBS}${XX}"
				#echo "$KBS $XX"
			fi
		done
	else
		Error "${FTP} does not exist."
	fi
}

# Future implementation - log all results.
LogResults () {
	#Encapsulate "Initiating Logging function... in ${CURRENT}"
	for EACH in "${LOG_FILE[@]}"
	do
		if [[ "${DEBUG}" ]]; then
			Encapsulate "Checking for ${EACH}"
		fi
		if [[ -f "/var/log/${EACH}" ]]; then
			#Encapsulate "Found ${EACH} Logging to ${LOG_FILE}"
			cat "edit/var/log/${EACH}" >> "${LOG_FILE}"
			echo "LOG FILE: ${EACH}" >> "README.TXT"
			echo "========" >> "README.TXT"
			cat "/var/log/${EACH}" >> "README.TXT"
		else
			Encapsulate "No error(s) to back up."
			#Encapsulate "Non-existant."
		fi
	done
	Encapsulate "${PROGNAME} --modify if you wish to make adjustments."
	FullBar
}

# Set a timer to display duration of download (s)
# Usage:  Timer [start|stop]
DownloadTimer () {
   	Tcmd="${1^^}"

    case "$Tcmd" in
        START) _StartSecs=$(date +%s)
            ;;
        STOP) _StopSecs=$(date +%s)
                [[ ! $_StartSecs ]] && Error "[Internal Error] Timer did not record a start time." && return
                ((_DiffSecs=_StopSecs-_StartSecs))
                DLAPSE=$(date -u -d@"$_DiffSecs" +"%-Hh%-Mm%-Ss")
            ;;
        *) Error "[Internal Error] Unknown arg ${Tcmd}"
            ;;
    esac

}

# Download various packages showing progression...
Download () {
    local url="${1}"
	FILENAME=$(echo "${url##*/}")
	if [[ -f "${FILENAME}" ]]; then
		Encapsulate "${FILENAME} exists, deleting for re-download."
		rm "${FILENAME}"
	fi
    Encapsulate "Downloading: ${1}"
	Encapsulate "Filename: ${FILENAME}"
	DownloadTimer "Start"
    wget --progress=dot $url 2>&1 | grep --line-buffered "%" | sed -u -e "s,\.,,g" | awk '\''{printf("\b\b\b\b%4s", $2)}'\''

    echo -ne "\b\b\b\b"
	DownloadTimer "Stop"
	FileSize "${FILENAME}"
	#echo $?
    Encapsulate "Download complete: ${FILENAME} ${FORMATTED} bytes (${TRUESIZE}). Download time: ${DLAPSE}"
}

# Dump data to the screen in pretty columns.
Columnize () {
	# Columnize is an internally called function exclusively.
	# EXAMPLE
	# -t to shove through the column titles we will count the number of switches and
	# calculate spacing eventually.
	if [[ "${1}" == "-t" ]]; then
		#echo -e "${bldgrn}Number of switches passed: $#"
		for ARG in "$@"
		do
			array_counter=$((array_counter + 1))
			if [[ "${array_counter}" -gt 2 ]]; then
				#echo "Switch ${array_counter}: ${ARG}"
				ARGUMENTS[${array_counter}]="${ARG}"
				tLen="${#ARGUMENTS[${array_counter}]}"
				if [[ $tLen -ge $WIDEST ]]; then
					WIDEST="${tLen}"
				fi
			fi
		done
	else
		for ARG in "$@"
		do
			array_counter=$((array_counter + 1))
			if [[ "${array_counter}" -gt 1 ]]; then
				ARGUMENTS[${array_counter}]="${ARG}"
				tLen="${#ARGUMENTS[${array_counter}]}"
				if [[ "$tLen" -ge "${WIDEST}" ]]; then
					WIDEST="${tLen}"
				fi
			fi
		done
	fi
	#echo "#: $# VARS: $*"
	#LONGESTLENGTH="${#2}"
	#echo "Length of ${2} is $LONGESTLENGTH"
	#echo ${COLUMNZ}
	MAINS=$(echo "scale=2; ${COLUMNZ}-30" | bc)
	MAINS=${MAINS%.*}
	#echo $MAINS
	MAINS=$((MAINS - 2))
	MAINS=$((MAINS / 4))
	#echo $MAINS
	if [[ "${1}" = "-t" ]]; then
		#"#" "DEV" "VENDOR" "LABEL" "TYPE" "SIZE"
		printf "%-0s %-32s %-11s %-16s %-7s %-3s %-16s %-1s\n" "▒" "${2}" "${3}" "${4}" "${5}" "${6}" "${7}" "${8}"
	else
		#MAINS=$(expr $MAINS / 2)
		printf "%-0s %-32s %-11s %-16s %-7s %-13s %-3s %-16s %-1s\n" "▒" "${1}" "${2}" "${3}" "${4}" "${5}" "${6}" "${7}" "${8}"
	fi
}

Error () {
	echo -en "${txtred}"
	Center "${1}" "--ERROR"
	echo -en "${txtrst}"
}

# for outputting to X-11 screen a notification of completion and playing sound.
# The sound file is from the "Optional" ultimate-edition-sound-theme
Notification () {
	# Is X11 running?
	X="${DISPLAY}"
	DISP=$(printf "[%s]\n" "${DISPLAY}" "${XAUTHORITY}" | grep ":0")

#	X=$(xdpyinfo -display :0) >/dev/null
	if [[ "${DEBUG}" ]]; then
		echo "DEBUG: $X"
	fi
	# Does the user have the optional UE Sound scheme installed?
	if [[ -f "/usr/share/sounds/Ultimate Edition Sound Scheme/stereo/itisdone.wav" ]]; then
		WAVE="1"
	fi
	# Is the user in an X11 GUI environment and have notification OSD installed?
	if [[ "${DISP}" && "${NOTIFY}" ]]; then
		notify-send "${APPNAME}" "${1}" -i /usr/share/ultimate_edition/logo.png -t 5000
	fi
	# Does the user have pre-requisites? If so, break out the Cylon voice.
	if [[ "${SOUND}" && "${WAVE}" && "${DISP}" ]]; then
		canberra-gtk-play --file "/usr/share/sounds/Ultimate Edition Sound Scheme/stereo/itisdone.wav" 2>/dev/null
	fi
	# Display message in terminal unconditionally
	Encapsulate "${1}"
}

# Usage: Eye Candy "Message"
# Example: Eye Candy "Repostorm $REPOVERSION is entering extraction mode."
# ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
# ▒ Repostorm 1.7.7 is entering extraction mode. ▒
# ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
EyeCandy () {
	# Verify a message has been sent to this otherwise do squat.

	STP="${1}"
	if [[ "${STP}" ]]; then
		STRLEN="${#STP}"
		((STRLEN=STRLEN + 3))
		GREPPED=$(echo "${STP}" | grep -E "\e")
		if [[ "${GREPPED}" ]]; then
			((STRLEN=STRLEN - 13))
		fi
		RR=0; while [[ "${RR}" -le "${STRLEN}" ]]; do echo -n "▒"; ((RR=RR+1)); done; echo;
		echo -e "${bldblu}▒${txtgrn} ${STP} ${bldblu}▒"
		RR=0; while [[ "${RR}" -le "${STRLEN}" ]]; do echo -n "▒"; ((RR=RR+1)); done; echo;
	fi
	echo -en "${txtrst}"
}

# Usage: Encapsulate
# Encapsulate "Repostorm 1.8.7 is entering extraction mode."
# Example: ▒ Repostorm 1.8.7 is entering extraction mode. ▒
Encapsulate () {
	# Verify a message has been sent to this otherwise do squat.
	# Example: Encapsulate ("Repostorm $REPOVERSION is entering extraction mode.")
	# ▒ Repostorm 1.7.7 is entering extraction mode.                       ▒

	STP="${1}"
	if [[ "${STP}" ]]; then
		STRLEN="${#STP}"
		((STRLEN=STRLEN + 3))
		((DISTANCE=COLUMNZ - STRLEN))
		GREPPED=$(echo "${STP}" | grep -E '\e')
		if [[ "${GREPPED}" ]]; then
			((STRLEN=STRLEN - 13))
		fi
		echo -en "${BRIGHT}${bldblu}▒ ${BRIGHT}${txtgrn}${STP}"
		RR=0; while [[ "${RR}" -lt "${DISTANCE}" ]]; do echo -n " "; ((RR=RR+1)); done; echo "${BRIGHT}${bldblu}▒";
	fi
	echo -en "${txtrst}"
}

# Center data passed to on screen
Center () {
	STP="${1}"
	ERROR="${2}"
	if [[ "${STP}" ]]; then
		STRLEN="${#STP}"
		((CENTER=STRLEN / 2 ))
		#CENTER=CENTER-1
		((TCENTER=COLUMNZ / 2 ))
		#TCENTER=TCENTER-1
		((DISTANCE=TCENTER - CENTER))
		((DISTANCE=DISTANCE - 2))
		if ! [[ "${ERROR}" ]]; then
			echo -en ""
		else
			echo -en "${txtred}"
		fi
		RR=0; while [[ "${RR}" -lt "${DISTANCE}" ]]; do echo -n "${BRIGHT}${bldblu}▒"; ((RR=RR+1)); done;
		echo -en "${BRIGHT}${txtgrn} ${STP} "
		if ! [[ "${ERROR}" ]]; then
			echo -en ""
		else
			echo -en "${txtred}"
		fi
		TT=0; while [ "${TT}" -lt "${DISTANCE}" ]; do echo -n "${BRIGHT}${bldblu}▒"; ((TT=TT+1)); done;
		((CALC=RR + TT + STRLEN + 2))
		if [[ "${CALC}" -lt "${COLUMNZ}" ]]; then
			while [[ "${CALC}" -lt "${COLUMNZ}" ]]; do echo -n "${BRIGHT}${bldblu}▒"; ((CALC=CALC+1)); done; echo;
		fi
	fi
	# echo "STRING LEN: ${STRLEN} CENTER: $CENTER TOTAL CNTER: $TCENTER RR:${RR} TT:${TT} COLUMNZ: ${COLUMNZ} CALC: ${CALC} DISTANCE: ${DISTANCE}"
	echo -en ""
}

# Draws a bar across the screen based on screen size detected (columnz)
FullBar () {
	RR=1; while [[ "${RR}" -le "${COLUMNZ}" ]]; do echo -n "${BRIGHT}${bldblu}▒"; ((RR=RR+1)); done; echo;
}

# Dump version information and exit function
VersionDump () {
	echo -en "${bldblu}"
	GREPIT=$(echo "$*" | grep "suppress")
	if ! [[ "${GREPIT}" ]]; then
		Center "${APPNAME} (${PROGNAME}) ${VERSION}, ${BUILDDATE}"
		Encapsulate "GNU ${PROGNAME} home page: <${WEBSITE}>."
		Encapsulate "E-mail bug reports to: ${EMAIL}."
		Encapsulate "Be sure to include the word ${PROGNAME} somewhere in the Subject: field."
		FullBar
	else
		echo "${APPNAME} (${PROGNAME}) ${VERSION}, ${BUILDDATE}"
		echo "GNU ${PROGNAME} home page: <http://${WEBSITE}/>."
		echo "E-mail bug reports to: ${EMAIL}."
		echo "Be sure to include the word ${PROGNAME} somewhere in the Subject: field."
	fi
	echo -en "${txtrst}"
}

# Set a timer to display duration ##
# Usage:  Timer [start|stop]
Timer () {
   	Tcmd="${1^^}"

    case "$Tcmd" in
        START) _StartSecs=$(date +%s)
            ;;
        STOP) _StopSecs=$(date +%s)
                [[ ! $_StartSecs ]] && Error "[Internal Error] Timer did not record a start time." && return
                ((_DiffSecs=_StopSecs-_StartSecs))
                TimeLapse=$(date -u -d@"$_DiffSecs" +"%-Hh%-Mm%-Ss")
                Encapsulate "Timer: $TimeLapse"
            ;;
        *) Error "[Internal Error] Unknown arg ${Tcmd}"
            ;;
    esac
}

# 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 "  -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
		ALL|v|version)
		Encapsulate "Usage version;"
		FullBar
		Center "${PROGNAME} -v"
		FullBar
		Encapsulate "Displays ${PROGNAME}s version number and exits."
		FullBar;;

		# Help Help
		ALL|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
	esac
	exit 0
}

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

case "${1}" in
      -h|--help|-\?) Help "$@"; exit 0;; # TODO: Enhance this section.
      -v|--version) VersionDump "$@"; exit 0;;
      *) Help; exit 0;;
    esac
'
