#!/bin/bash

# ==============================================================================
# title			:donors
# description	:Splits csv files to manage list of donors automously
# author		:Glenn Cady <TheeMahn@ultimateedition.info>
# date			:05/18/2016
# version		:1.9.7
# usage			:donors --help
# manual		:man donors
# notes			:See change-log below for further information.
# ==============================================================================
# Change-log: 1.0: unreleased
#
#			1.9.3: Initiated full automous control.
# ==============================================================================

# Modify the below information to correlate with the software you are designing.
PROGNAME="donors"
PROGRAMMER="TheeMahn"
BUILDDATE="05/18/2016"
VERSION="1.9.7"
WEBSITE="ultimateedition.info"
EMAIL="<$PROGRAMMER@$WEBSITE>"


# ==============================================================================
# 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"

# ==============================================================================
# Varibles
SPLIT=0

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

# ==============================================================================
# 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

# Retrieve the number of lines the TTY has.
LINEZ=$(tput lines)

# Retrieve the number of columns the TTY has.
COLUMNZ=$(tput cols)

# Optional graphical notification, see if user has it installed.
NOTIFY=$(which notify-send)

# Optional sound notification, see if user has it installed.
SOUND=$(which canberra-gtk-play)

# Internal varible used for doing eyecandy
declare -i RR
RR=0

# Declare Arrays for storing data
declare -a DATES
declare -a PERSONS
declare -a COUNTRYS
declare -a AMOUNTS

ARRAY=0
FILETOPROCESS="donors.csv"


# Info for determining current user to possibly compare against later
IUSER=${SUDO_USER:-$USER}
IHOME=/home/$IUSER

# set colors so errors etc. stand out.
txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
badgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset

# Begin programming here.
function SplitData(){
# Allow for custom file processing.
if [[ $2 != "" ]]; then
	if ! [[ -f $2 ]]; then
		echo "File not found $2. Exiting."
		exit 1
	else
		FILETOPROCESS=$2
	fi
else
	if ! [[ -f $FILETOPROCESS ]]; then
		echo "File not found $FILETOPROCESS. Exiting."
		exit 1
	fi
fi

# Populate arrays with data.  Date the donor donated.
readarray -t DATES < <(cut -d'"' -f2 $FILETOPROCESS)
DATES=("${DATES[@]#*,}")
DATES=("${DATES[@]%%,*}")
printf '%s\n' "${DATES[0]}"

# Populate arrays with data.  Name of the awesome individual who donated.
readarray -t NAMES < <(cut -d'"' -f8 $FILETOPROCESS)
NAMES=("${NAMES[@]#*,}")
NAMES=("${NAMES[@]%%,*}")
printf '%s\n' "${NAMES[0]}"

# Populate arrays with data.  Country donated from.
readarray -t COUNTRYS < <(cut -d'"' -f18 $FILETOPROCESS)
COUNTRYS=("${COUNTRYS[@]#*,}")
COUNTRYS=("${COUNTRYS[@]%%,*}")
printf '%s\n' "${COUNTRYS[0]}"

# Populate arrays with data.  The amount the donor donated.
readarray -t AMOUNTS < <(cut -d, -f3 $FILETOPROCESS)
AMOUNTS=("${AMOUNTS[@]#*,}")
AMOUNTS=("${AMOUNTS[@]%%,*}")
printf '%s\n' "${AMOUNTS[0]}"

# Obtain the number of donors
TOTALDONORS=${#DATE[*]}
echo "Total Donors to process: $TOTALDONORS"

# Generate individual columns with it's perspective data of donors.
# Each person's Name as it cycles through the entire array of $NAMES[@]

for PERSON in "${NAMES[@]}"
do
	DATE=${DATES[$ARRAY]}
	COUNTRY=${COUNTRYS[$ARRAY]}
	AMMOUNT=${AMOUNTS[$ARRAY]}
	echo "$PERSON $DATE $COUNTRY $AMMOUNT"
	# Increment the value of the current array to coincide with the
	# value of the next person to process.
	ARRAY=$((ARRAY+1))
done
Center "Processing of $FILETOPROCESS complete."
}


#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
function Percent () {
	echo "scale = $3; $1 * 100 / $2" | bc
}

# Debugging function to monitor passed arguments.
function CommandLineInterpreter () {
	#echo -e "${bldgrn}Number of switches passed: $#"
	for var in "$@"
	do
		array_counter=$(($array_counter + 1))

		#echo "Switch $array_counter: $var"
	done
}

# Future implementation - log all chGlenn Cady results.
function LogResults () {
	Encapsulate "Initiating Logging function... in $PWD"
	for EACH in ${LOGFILEZ[@]}
	do
		Encapsulate "Checking for $EACH"
		if [[ -f edit/var/log/$EACH ]]; then
			Encapsulate "Found $EACH Logging to ${LOG_FILE}"
			cat edit/var/log/$EACH >> ${LOG_FILE}
			echo "LOG FILE: $EACH" >> extract-cd/README.TXT
			echo "========" >> extract-cd/README.TXT
			cat edit/var/log/$EACH >> extract-cd/README.TXT
		else
			Encapsulate "Non-existant."
		fi
	done
}

# Download various packages showing progression...
function Download() {
	local url=$1
	echo -n "    "
	wget --progress=dot $url 2>&1 | grep --line-buffered "%" | \
	sed -u -e "s,\.,,g" | awk "{printf("%4s", $2)}"
	echo -ne ""
	Encapsulate "Done."
}

# BEGIN CODE Borrowed from TMOSB, massively customized. This function when
# written fully will enter code cleanup application  and I will not look back ;)
function 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
				#echo "Length of ${ARGUMENTS[$array_counter]} is $tLen"
			fi
			#echo "The widest passed varible is $WIDEST"
		done
	else
		#echo -e "${bldgrn}Number of switches passed: $#"
		for ARG in "$@"
		do
			array_counter=$(($array_counter + 1))
			if [[ $array_counter -gt 1 ]]; then
				#echo "Switch $array_counter: $ARG"
				ARGUMENTS[$array_counter]=$ARG
				tLen=${#ARGUMENTS[$array_counter]}
				if [[ $tLen -ge $WIDEST ]]; then
					WIDEST=$tLen
				fi
				#echo "Length of ${ARGUMENTS[$array_counter]} is $tLen"
			fi
			#echo "The widest passed varible is $WIDEST"
		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=$(expr $MAINS - 2)
	MAINS=$(expr $MAINS / 4)
	#echo $MAINS
	if [[ $1 = "-t" ]]; then
		#"#" "DEV" "VENDOR" "LABEL" "TYPE" "SIZE"
		printf "%-0s %-16s %-7s %-16s %-7s %-3s %-13s %-3s %-16s %-1s
" "▒" "$2" "$3" "$4" "$5" "$6" "$7" "$8"
	else
		#MAINS=$(expr $MAINS / 2)
		printf "%-0s %-16s %-7s %-16s %-7s %-3s %-13s %-3s %-16s %-1s
" "▒" "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8"
	fi
}

# Usage: Eye Candy "Message"
function EyeCandy() {
	# Verify a message has been sent to this function otherwise do squat.
	# ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
	# ▒ Repostorm 1.8.4 is entering extraction mode. ▒
	# ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
	STP="$1"
	if [[ $STP ]]; then
		STRLEN=${#STP}
		STRLEN=$(expr $STRLEN + 3)
		GREPPED=$(echo $STP | grep -E e)
		if [[ $GREPPED ]]; then
			STRLEN=$(expr $STRLEN - 13)
		fi
		RR=0; while [ $RR -le $STRLEN ]; do echo -n "▒"; RR=RR+1; done; echo;
		echo -e "▒ "$STP" ▒"
		RR=0; while [ $RR -le $STRLEN ]; do echo -n "▒"; RR=RR+1; done; echo;
	fi
}

function Encapsulate() {
	# Verify a message has been sent to this function otherwise do squat.
	# ▒ Repostorm 1.8.4 is entering extraction mode.                       ▒

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

# Function for outputting to X-11 screen a notification of completion and playing sound.
# The sound file is from the "Optional" ultimate-edition-sound-theme
function Notification () {
	# Is X11 running?
	X=$( pidof X )
	# 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 [[ $X && $NOTIFY ]]; then
		a=$(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 ]]; then
		a=$(canberra-gtk-play -i itisdone 2>/dev/null)
	fi
	# Display message in terminal unconditionally
	Encapsulate $1
}

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

# Center data passed to function on screen
function Center () {
	STP=$1
	if [[ $STP ]]; then
		STRLEN=${#STP}
		CENTER=$(expr $STRLEN / 2 )
		#CENTER=CENTER-1
		TCENTER=$(expr $COLUMNZ / 2 )
		#TCENTER=TCENTER-1
		DISTANCE=$(expr $TCENTER - $CENTER)
		DISTANCE=$(expr $DISTANCE - 2)
		echo -en "${txtrst}"
		RR=0; while [ $RR -lt $DISTANCE ]; do echo -n "▒"; RR=RR+1; done;
		echo -en "${bldgrn} $STP ${txtrst}"
		TT=0; while [ $TT -lt $DISTANCE ]; do echo -n "▒"; TT=TT+1; done;
		CALC=$(expr $RR + $TT + $STRLEN + 2)
		if [[ $CALC -lt $COLUMNZ ]]; then
			ZZZ=0; while [ $CALC -lt $COLUMNZ ]; do echo -n "▒"; CALC=CALC+1; done; echo;
		fi

		# Dubugging:

	fi		# echo "STRING LEN: $STRLEN CENTER: $CENTER TOTAL CNTER: $TCENTER RR=$RR TT=$TT COLUMNZ: $COLUMNZ CALC: $CALC DISTANCE: $DISTANCE"
}

function Error () {
	echo -en "${bldred}"
	FullBar
	Center "$1"
	echo -en "${bldred}"
	FullBar
	echo -en "${txtrst}"
}
# Version dump header
function VersionDump {
	if [[ -w ${LOG_FILE} ]]; then
		echo -e "${undwht}$APPNAME ($PROGNAME) $VERSION, $BUILDDATE${txtrst}" 2>&1 | tee ${LOG_FILE}
		echo "GNU $PROGNAME ("$APPNAME") home page: <http://$WEBSITE/>." 2>&1 | tee --append ${LOG_FILE}
		# echo "COMMAND EXECUTED: "$* | tee --append ${LOG_FILE}
	else
		echo -e "${undwht}$APPNAME ($PROGNAME) $VERSION, $BUILDDATE${txtrst}"
		echo "GNU $PROGNAME ("$APPNAME") home page: <http://$WEBSITE/>."
	fi
	echo "E-mail bug reports to: $EMAIL."
	echo "Be sure to include the word $PROGNAME somewhere in the Subject: field."
}

function VersionDump {
	GREPIT=$(echo $* | grep "suppress")
	if ! [[ $GREPIT ]]; then
		Center "$APPNAME ($PROGNAME) $VERSION, $BUILDDATE"
		Encapsulate "GNU $PROGNAME home page: <http://$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
}

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

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

	case $PRAM in
		ALL)
		echo -e "${bldgrn}Usage: $PROGNAME -<-COMMAND> [OPTION]${txtrst}"
		echo -e "Mandatory arguments to long options are identical for short options."
		echo -e "  possible commands..."
		echo -e ""
		echo -e "  -h	--help		this help message"
		echo -e "  -s	--split		Splits [FILENAME] into chunks for label processing."
		echo -e "  -v	--version	dump version info and exit"
		echo -e ""
		echo -e "${bldgrn}$PROGNAME --help [COMMAND] for further information.${txtrst}";;
		ALL|s|split)
		echo -e ""
		echo -e "${bldwht}Usage split;${txtrst}"
		echo -e "${txtgrn}$PROGNAME -s [FILENAME]${txtrst}"
		echo -e "Splits [FILENAME] into chunks for label processing."
		echo -e "Not specifying then [OPTIONAL] filename will search for inv.csv";;
		ALL|v|version)
		echo -e ""
		echo -e "${bldwht}Usage version;${txtrst}"
		echo -e "${txtgrn}$PROGNAME -v${txtrst}"
		echo -e "Displays $PROGNAME version number and exits.";;
		ALL|h|help|\?)
		echo -e ""
		echo -e "${bldwht}Useage Help [COMMAND];${txtrst}"
		echo -e "${txtgrn}$PROGNAME -h [COMMAND]${txtrst}"
		echo "Displays this message. For futher information $PROGNAME help [COMMAND]"
		echo -e "or refer to the manpages."
		echo -e ""
		echo -e "man $PROGNAME"
		echo -e "${txtgrn}"
		echo -e "Example: $PROGNAME -h version"
		echo -e "${txtwht}Will display help about the command version${txtrst}"
	esac
	exit 0
}


# Command line pre-processor - this section of code is where your functions are called.

    case "$1" in
      -h|--help|-\?) Help $*; exit 0;;
      -v|--version) VersionDump; exit 0;;
      -s|--split) SplitData $*; exit 0;;
      *) Help; exit 0;;
    esac


