#!/bin/sh

srcfile=$(pwd)/.srcfile

usage() {
	cat <<EOF
src
manages source directories

Usage: src [COMMAND]

Commands:
	update		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_gitrepo() {
	## Add this git repo to the srcfile
	echo "git" "$1" "$2" >> "$srcfile"
}

rm_entry() {
	## Remove this entry from the srcfile
	tmp="$srcfile.tmp"

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

update_gitrepo() {
	## Update/clone this git repo
	if ! [ -d "$2" ] ; then
		git clone "$1" "$2"
		updated="$updated $2"
	else
		git -C "$2" pull 
	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
}

parse() {
	## Parse srcfile and update everything
	srcfile=$(pwd)/.srcfile

	if ! [ -f "$srcfile" ] ; then
		echo ".srcfile not found!"
		exit 1
	fi

	awk '!($$0 ~ /^#/) { print }' "$srcfile" | while read -r type url path; do
		case "$type" in
			"git")
				echo "Updating: $path"
				update_gitrepo "$url" "$path"
				;;
			"tar")
				echo "Updating: $path"
				#update_tarfile "$url" "$path"
				;;
			*)
				echo "Not a valid source type: $type"
				continue
				;;
		esac
	done

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

for arg in "$@" ; do
	case "$arg" in
		--help)
			usage
			exit 1
			;;
		--version)
			echo "src version 0.1.0"
			exit 1
			;;
		*)
			echo "Invalid command line args"
			exit 1
			;;
	esac
done

parse
