#!/usr/bin/env bash
# Prepares templates for release.

set -euo pipefail
trap 'cd "${PWD}"' EXIT
cd "$(dirname "$0")"

# get the version number from the command line argument
if [[ $# -ne 1 ]]; then
	echo "Usage: $0 <version>"
	exit 1
fi
version=$1

version=${version#"v"}
echo "Preparing release for version ${version}"
cd ..

# Update the version in the sdk.json file
jq --arg ver "${version}" '.sdk.version = $ver' sdk.json >tmp.json && mv tmp.json sdk.json

# Update the version of the sdk used in the templates
cd templates
for template in *; do
	if [[ -d ${template} ]]; then
		cd "${template}"

		# Remove any output files
		rm -rf node_modules
		rm -rf build

		# Remove the lockfile - it will be regenerated by npm install when the template is used.
		rm -f package-lock.json

		# Update the version of the modus-sdk-as dependency to match the release version.
		if [[ ${OSTYPE} == "darwin"* ]]; then
			sed -i '' 's/"@hypermode\/modus-sdk-as": "..\/..\/src"/"@hypermode\/modus-sdk-as": "^'"${version}"'"/' package.json
		else
			sed -i 's/"@hypermode\/modus-sdk-as": "..\/..\/src"/"@hypermode\/modus-sdk-as": "^'"${version}"'"/' package.json
		fi

		cd ..
	fi
done
cd ..

# Create a tarball of the templates
tar -czvf templates_assemblyscript_v"${version}".tar.gz templates

# set the version in the package.json file
cd src
npm version "${version}" --no-git-tag-version
cd ..
