#!/bin/sh

srcfile=$(pwd)/.srcfile

usage() {
	## Print usage information
	cat <<EOF
src
manages source directories

Usage: src [COMMAND]

Commands:
	up		Update source directory
	ls		List managed directories
	add		Add a source
	rm		Remove a source directory

Flags:
	--help, -h	Displays this help
	--version, -v	Show version and exit
EOF
}

add_item() {
	## Add this item repo to the srcfile
	echo "$1" "$2" "$3" >> "$srcfile"
}

rm_item() {
	## Remove this entry from the srcfile
	## and delete the source files afterwards
	tmp="$srcfile.tmp"

	awk "\$3 != \"$1\" { print }" "$srcfile" > "$tmp"
	mv "$tmp" "$srcfile"

	rm -rf "$1"
}

update_gitrepo() {
	## Update/clone this git repo
	if ! [ -d "$2" ] ; then
		git clone "$1" "$2"
		updated="$updated $2"
	else
		count=$(git -C "$2" pull | wc -l)
		if [ "$count" -gt 1 ] ; then
			updated="$updated $2"
		fi
	fi
}

update_tarfile() {
	## Download and extract this tarfile if it
	## doesn't exist yet
	if ! [ -d "$2" ] ; then
		wget "$1"
		tar -xf "$1" -C "$2"
		updated="$updated $2"
	else
		echo "Already downloaded"
	fi
}

update_item() {
	## Updates an individual item
	case "$1" in
		"git")
			echo "Updating: $3"
			update_gitrepo "$2" "$3"
			;;
		"tar")
			echo "Updating: $3"
			update_tarfile "$2" "$3"
			;;
		*)
			echo "Not a valid source type: $1"
			errors="$errors $3"
			;;
	esac
}

preproc() {
	## Preprocess the srcfile (remove comments etc.)
	if ! [ -f "$srcfile" ] ; then
		echo ".srcfile not found!"
		exit 1
	fi

	tmp="$srcfile.tmp"
	sed 's/^#.*//; /^\s*$/d' < "$srcfile" > "$tmp"
}

cleanup() {
	## Cleanup everything (temp files)
	rm "$tmp"
}

update_all() {
	## Parse srcfile and update everything
	preproc

	while read -r type url path; do
		update_item "$type" "$url" "$path"
	done < "$tmp"

	case "$errors" in
		"")
			;;
		*)
			echo "Errors occurred during:$updated"
			;;
	esac

	case "$updated" in
		"")
			echo "Nothing updated"
			;;
		*)
			echo "Updated:$updated"
			;;
	esac

	cleanup
}

list_all() {
	## Parse srcfile and update everything
	preproc

	while read -r type url path; do
		echo "$type" "$url" "$path"
	done < "$tmp"

	cleanup
}

case "$1" in
	"up")
		update_all
		;;
	"add")
		add_item "$2" "$3" "$4"
		update_item "$2" "$3" "$4"
		;;
	"rm")
		rm_item "$2"
		;;
	"ls")
		list_all
		;;
	"--help"|"-h")
		usage
		exit 1
		;;
	"--version"|"-v")
		echo "src version 0.1.0"
		exit 1
		;;
	*)
		echo "Invalid command or flag"
		exit 1
		;;
esac
