#!/bin/bash

# Commits updates to apps, allowing you to edit the commit messages

commands=()

while read line; do
	if [[ "$line" == *M*metadata/*.txt ]]; then
		file=${line##* }
		
		id=${file##*/}
		id=${id%.txt*}
		if [ $# -gt 0 ]; then
			found=false
			for arg in "$@"; do
				if [ "$id" == "$arg" ]; then
					found=true
					break
				fi
			done
			$found || continue
		fi

		[ -d metadata/$id ] && extra=metadata/$id

		name=
		while read l; do
			if [[ "$l" == "Auto Name:"* ]]; then
				name=${l##*:}
				break
			fi
		done < "$file"

		[ -n "$name" ] && fullname="$name ($id)" || fullname=$id

		newbuild=0
		while read l; do
			if [[ "$l" == "+Build:"* ]]; then
				newbuild=1
				build=${l#*:}
				version=${build%%,*}
				build=${build#*,}
				vercode=${build%%,*}
			fi
		done < <(git diff HEAD -- "$file")

		if [ $newbuild -eq 0 ]; then
			message="$fullname:"
		else
			message="Update $fullname to $version ($vercode)"
		fi

		commands+=("git commit -m '$message' -e -v -- $file $extra")
	fi
done < <(git status --porcelain)

for cmd in "${commands[@]}"; do
	eval "$cmd"
done

