#!/bin/sh
set -e

# git remote add cmock https://github.com/ThrowTheSwitch/CMock

commit=${1:-cmock/master}
name=${2:-CMock}

upsver=$(git describe --tags ${commit})
upsver=${upsver%-*-*}
upsver=${upsver%+git*}
gitver=$(git describe --match ${upsver} --tags ${commit})
gitver=${gitver#v}
tagver=${gitver%%-*}
gitver=${gitver#${tagver}-}
snapver=${tagver}+git${gitver}
prefix=${name}-${snapver}
tarball=${prefix}.tar
tarxzball=${tarball}.xz
tag=v${snapver}

test "$(git rev-parse HEAD)" = "$(git rev-parse ${commit})"
git submodule update
tmp=$(mktemp -d)
git archive --format=tar --prefix=${prefix}/ ${commit} | tar xf - -C ${tmp}
for submodule in $(git submodule foreach --quiet 'echo $sm_path')
do
	(cd ${submodule} && git archive --format=tar --prefix=${prefix}/${submodule}/ HEAD) | tar xf - -C ${tmp}
done
tar cf - --sort=name -C ${tmp} ${prefix} | xz -9 > ${tarxzball}
rm -rf ${tmp}

echo "Exported to ${tarxzball}"

git tag ${tag} ${commit}

echo "Tagged as ${tag}"
