#!/bin/bash -e

x=`git symbolic-ref -q HEAD`
thisbranch=${x##refs/heads/}
origbranch=${thisbranch#snap/}
snapbranch=snap/${origbranch}

if [[ $thisbranch != $snapbranch ]]; then
	if git rev-parse "$snapbranch" -- >&/dev/null; then
		# $snapbranch exists
		# switch branches to $snapbranch; save changes (by stashing them)
		# and reapply them
		nostash=true
		status=`git status --porcelain=v1 | grep -Fv '?'`
		if [[ $status ]]; then
			git stash
			nostash=false
		fi
		git checkout "$snapbranch" --
		git rebase -p "$origbranch"
		$nostash || git stash pop
	else
		# $snapbranch doesn't exist
		git checkout -b "$snapbranch" "$origbranch" --
	fi
fi

git commit -am "Snapshot of $thisbranch on $(date)"

# vim:noet:sw=8:sts=8:ts=8
