#!/usr/bin/bash

# Prepares source tarball with submodules
# Takes a while! Only 300+MB but many submodules

readonly url='https://github.com/nesbox/TIC-80.git'
readonly name='tic80'
readonly cloned="${name}-cloned"

# Non-shallow clone because we need the git history (don't use --depth=1)
# Submodules can be shallow
git clone --single-branch \
	--recurse-submodules --shallow-submodules \
	-- "${url}" "${cloned}" || exit 50


readonly target="${cloned}/CMakeLists.txt"
# Get major and minor versions
verx="$(grep -Po '^set\(VERSION_MAJOR \K[\d]+' "${target}")" || exit 60
readonly verx
very="$(grep -Po '^set\(VERSION_MINOR \K[\d]+' "${target}")" || exit 61
readonly very

# Get the current short commit hash
hash="$(git -C "${cloned}" rev-parse --short=7 HEAD)" || exit 65
readonly hash
# Get the number of commits (upstream uses it as the Z in X.Y.Z)
verz="$(git -C "${cloned}" rev-list HEAD --count)" || exit 66
readonly verz

# Patch CMakeLists.txt to hard code these 2 values
readonly pattern='^set(VERSION_REVISION .*)$'
readonly replace="set(VERSION_REVISION ${verz})\nset(VERSION_HASH \"${hash}\")"
sed -i -e "s/${pattern}/${replace}/" "${target}" || exit 69


# Now we can delete all git files
find "${cloned}" -name '.git*' -exec rm -rf -- '{}' \+ || exit 70

# Create tarball
readonly final_name="${name}-${verx}.${very}.${verz}_${hash}"
mv "${cloned}" "${final_name}" || exit 80
tar czf "${final_name}.tar.gz" "${final_name}" || exit 85

rm -rf -- "${final_name}" || exit 90
