#!/usr/bin/env bash
set -euo pipefail

version="${1:-dev}"
output="${2:-dist/ht-portal-mobile-vpn-${version}-source.tar.gz}"
root="$(git rev-parse --show-toplevel)"
temporary="$(mktemp -d)"
trap 'rm -rf "$temporary"' EXIT

if ! git -C "$root" rev-parse --verify HEAD >/dev/null 2>&1; then
	echo >&2 "Source packaging requires a committed release revision."
	exit 1
fi

mkdir -p "$(dirname "$output")" "$temporary/ht-portal-mobile-vpn/third_party/n3n"
git -C "$root" archive HEAD | tar -x -C "$temporary/ht-portal-mobile-vpn"
git -C "$root" rev-parse HEAD > "$temporary/ht-portal-mobile-vpn/SOURCE_REVISION"
git -C "$root/third_party/n3n" archive HEAD | tar -x -C "$temporary/ht-portal-mobile-vpn/third_party/n3n"
git -C "$root/third_party/n3n" rev-parse HEAD > "$temporary/ht-portal-mobile-vpn/third_party/n3n/UPSTREAM_COMMIT"
git -C "$temporary/ht-portal-mobile-vpn/third_party/n3n" apply "$temporary/ht-portal-mobile-vpn/patches/n3n/embedded-mobile-integration.patch"
tar -czf "$output" -C "$temporary" ht-portal-mobile-vpn
echo "$output"
