#!/bin/sh
# Create a vendor tarball containing pre-fetched zig dependencies.
# Run this with network access before building the Debian package.
#
# Usage: ./mk_vendor_tarball.sh [version]
# Output: ../ghostty_VERSION.orig-zigcache.tar.gz

set -e

VERSION="${1:-1.3.1}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WORKDIR="$(mktemp -d)"
CACHE_DIR="$WORKDIR/vendor"

trap 'rm -rf "$WORKDIR"' EXIT

echo "Downloading ghostty $VERSION source tarball..."
wget -q "https://release.files.ghostty.org/$VERSION/ghostty-$VERSION.tar.gz" \
    -O "$WORKDIR/ghostty-$VERSION.tar.gz"
tar xf "$WORKDIR/ghostty-$VERSION.tar.gz" -C "$WORKDIR"

echo "Fetching zig dependencies into $CACHE_DIR..."
mkdir -p "$CACHE_DIR"
ZIG_GLOBAL_CACHE_DIR="$CACHE_DIR" \
    "$WORKDIR/ghostty-$VERSION/nix/build-support/fetch-zig-cache.sh"

echo "Cleaning vendored dependencies..."
# Remove macOS resource fork files (from JetBrains Mono, Nerd Fonts, and
# Dear ImGui bindings, whose upstream tarballs are created on macOS).
find "$CACHE_DIR" -name '._*' -delete
# Remove prebuilt Windows binaries and help files.
# zlib: .NET help file
rm "$CACHE_DIR"/p/*/contrib/dotzlib/DotZLib.chm
# gettext: C# test executable
rm "$CACHE_DIR"/p/*/gettext-tools/m4/csharpexec-test.exe
# breakpad: Windows tools and test data
rm "$CACHE_DIR"/p/*/src/tools/windows/binaries/dump_syms.exe \
      "$CACHE_DIR"/p/*/src/tools/windows/binaries/symupload.exe \
      "$CACHE_DIR"/p/*/src/tools/windows/dump_syms/testdata/dump_syms_regtest64.exe \
      "$CACHE_DIR"/p/*/src/tools/windows/dump_syms/testdata/pe_only_symbol_test.dll
# Remove breakpad's convert_UTF files: lintian flags license-problem-convert-utf-code
# and they are only used by breakpad's autotools build, not zig.
# The wildcard matches zig's content-addressed hash directory name
# (currently N-V-__8AALw2uwF_03u4JRkZwRLc3Y9hakkYV7NKRR9-RIZJ).
rm "$CACHE_DIR"/p/*/src/common/convert_UTF.cc \
      "$CACHE_DIR"/p/*/src/common/convert_UTF.h
# Remove empty directories left behind.
find "$CACHE_DIR" -type d -empty -delete

echo "Creating zigcache tarball..."
tar czf "$SCRIPT_DIR/../ghostty_$VERSION.orig-zigcache.tar.gz" \
    -C "$WORKDIR" vendor --transform 's/^vendor/zigcache/'

echo "Created ghostty_$VERSION.orig-zigcache.tar.gz"
