#!/bin/sh

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

Usage: src

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

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

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"
				gitrepo "$url" "$path"
				;;
			"tar")
				echo "Updating: $path"
				#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
