#!/usr/bin/env sh

REPOS_TO_SYNC="$REPO_SYNC"
ORIGIN="origin"

if [ -z "$REPOS_TO_SYNC" ]
then
	printf >&2 "The REPO_SYNC environment variable is empty, not doing anything!\n"
	exit 0
fi

for REPO_PAIR in $REPOS_TO_SYNC
do
	REMOTE="$(echo "$REPO_PAIR" | cut -d";" -f 1)"
	LOCAL="$(echo "$REPO_PAIR" | cut -d";" -f 2)"

	printf "git sync: '%s' to '%s'\n" "$REMOTE" "$LOCAL"

	if [ -d "$LOCAL" ]
	then
		if [ -n "$(git -C "$LOCAL" status --porcelain)" ]
		then
			git -C "$LOCAL" add --all || continue
			git -C "$LOCAL" commit --all -m "Simple sync"
		fi
		git -C "$LOCAL" pull "$ORIGIN" --rebase || continue
		git -C "$LOCAL" push "$ORIGIN" || continue
	else
		PARENT="$(dirname "$LOCAL")"
		if [ ! -d "$PARENT" ]; then mkdir -p "$PARENT"; fi
		git clone "$REMOTE" "$LOCAL"
	fi
done
