#!/bin/bash
declare -a directories=(
	"~/Documents/setup"
	"~/org"
	"~/matlab"
	"~/tex"
	)


divider="======================================================================="
git="/.git"
noCommits=0

if [ $# -gt 0 ]; then
	if [ $1 == p ]; then
		flag="p"
	elif [ $1 == c ]; then
		flag="c"
	elif [ $1 == s ]; then
		flag="s"
	else
		echo "wrong flag"
		exit 1
	fi
else
	echo "no arguments"
	exit 1
fi

for dir in "${directories[@]}"
do
	eval gitdir=$dir$git
	if [[ -d "$gitdir" ]]; then
		if [ $flag == p ]; then
			echo -e "\n"$divider
			echo -e "$dir"
			echo $divider
			eval "git -C $dir pull --all"

		elif [ $flag == c ]; then
			OUTPUT=$(eval git -c color.status=always -C $dir status )
			noCommit=$(echo $OUTPUT | grep -q "nothing to commit, working directory clean")$?
			if [[ $noCommit -eq 1 ]]; then
				echo -e "\n"$divider
				echo -e "$dir"
				echo $divider
				eval "git -C $dir commit -a"
				noCommits=1
			fi

		elif [ $flag == s ]; then
			OUTPUT=$(eval git -c color.status=always -C $dir status )
			noCommit=$(echo $OUTPUT | grep -q "nothing to commit, working directory clean")$?
			upToDate=$(echo $OUTPUT | grep -q "Your branch is up-to-date")$?
			isAhead=$(echo $OUTPUT | grep -q "Your branch is ahead")$?
			hasUntracked=$(echo $OUTPUT | grep -q "Untracked files")$?

			if [[ $upToDate -eq 1 ]] || [[ $noCommit -eq 1 ]]; then
				noCommits=1
				echo -e "\n"$divider
				echo "$dir"
				echo $divider
				echo "$OUTPUT"

				if [[ $isAhead -eq 0 ]]; then
					echo "Push changes to origin? [Y/n]"
					read answer
					if [[ $answer == Y ]] || [[ $answer == y ]] || [[ -z "${answer}" ]]; then
						eval "git -C $dir push"
					fi
				fi

				if [[ $hasUntracked -eq 0 ]]; then
					echo "Add untracked files? [Y/n]"
					read answer
					if [[ $answer == Y ]] || [[ $answer == y ]] || [[ -z "${answer}" ]]; then
						eval "git -C $dir add -A $dir"
						eval "git -C $dir status"
					fi
				fi
			fi
		fi
	fi
done

if [[ ( $flag == s ) && ( $noCommits -eq 1 ) ]]; then
	echo -e "\n"$divider
	echo $divider
	echo "Commit all? [Y/n]"
	read answer
	if [[ $answer == Y ]] || [[ $answer == y ]] || [[ -z "${answer}" ]]; then
		eval "gitall c"
	fi
fi

if [[ ( $flag == s ) && ( $noCommits -eq 0 ) ]]; then
	echo -e "\n"$divider
	echo "nothing to be done"
	echo $divider
fi

if [[ ( $flag == c ) && ( $noCommits -eq 0 ) ]]; then
	echo -e "\n"$divider
	echo "nothing to commit, all done"
	echo $divider
fi

