#!/bin/sh
# The release bundle (docs/dev/amalgamation.md): pic.c, the vendored dependency sources as they
# are, a README with the one build line, SHA256SUMS, and a tarball of the directory.
#
#   sh tools/amalgamation.sh OUTDIR NAME FILE.c...      (the Makefile passes $(PIC_SRC))
#
# Writes OUTDIR/NAME/ and OUTDIR/NAME.tar.gz. Run from the repository root.
set -eu
[ $# -ge 3 ] || { echo "usage: amalgamation.sh OUTDIR NAME FILE.c..." >&2; exit 2; }
base=$1
out=$1/$2
name=$2
shift 2

# Everything the plain build needs, and why. The dependencies are compiled as shipped, so their
# configuration arrives as -D flags.
FLAGS='-DHAVE_LIBFOSSIL_CONFIG_H -DWITHOUT_ICONV -DZ_HAVE_UNISTD_H -DSQLITE_THREADSAFE=1 -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_MATH_FUNCTIONS -DSQLITE_OMIT_LOAD_EXTENSION'

rm -rf "$out" "$out.tar.gz"
mkdir -p "$out/licenses"

sh tools/amalgamate.sh "$@" > "$out/pic.c"

cp vendor/libfossil/libfossil.c vendor/libfossil/libfossil.h vendor/libfossil/libfossil-config.h \
	vendor/libfossil/sqlite3.c vendor/libfossil/sqlite3.h "$out/"
cp vendor/zlib/*.c vendor/zlib/*.h "$out/"
cp vendor/bearssl/inc/*.h vendor/bearssl/src/*.h vendor/bearssl/src/*.c vendor/bearssl/src/*/*.c "$out/"
cp LICENSE "$out/licenses/pic"
cp vendor/libfossil/LICENSE "$out/licenses/libfossil-and-sqlite"
cp vendor/zlib/LICENSE "$out/licenses/zlib"
cp vendor/bearssl/LICENSE.txt "$out/licenses/bearssl"

# One directory, so two sources of the same name would silently overwrite each other.
dups=$(for d in vendor/libfossil vendor/zlib vendor/bearssl/inc vendor/bearssl/src vendor/bearssl/src/*; do
	[ -d "$d" ] && ls "$d" | grep '\.[ch]$' || true
done | sort | uniq -d)
[ -z "$dups" ] || { echo "amalgamation.sh: same name in two vendor directories: $dups" >&2; exit 1; }

cat > "$out/README" <<README
$name

pic, a durable coding agent in C11, as plain C sources. pic.c is all of pic's own code as one
translation unit. libfossil.c, sqlite3.c, zlib's files and BearSSL's files are the vendored
dependencies, unchanged. Build with a C11 compiler, libc, libm and pthread; nothing else is linked:

    cc -O2 $FLAGS *.c -o pic -lm -lpthread

The flags configure the dependencies: libfossil reads libfossil-config.h and is built without
iconv, zlib includes unistd.h, and SQLite is built with FTS5, the math functions, no loadable
extensions and serialized threading, as pic uses it. Compiling all the files takes a minute or so.

Licenses are in licenses/. SHA256SUMS lists every file.
README

(cd "$out" && for f in *; do [ -f "$f" ] && echo "$f"; done; for f in licenses/*; do echo "$f"; done) | LC_ALL=C sort |
	while read -r f; do
		if command -v sha256sum >/dev/null 2>&1; then (cd "$out" && sha256sum "$f"); else (cd "$out" && shasum -a 256 "$f"); fi
	done | grep -v ' SHA256SUMS$' > "$out/SHA256SUMS.new"
mv "$out/SHA256SUMS.new" "$out/SHA256SUMS"
tar -C "$base" -czf "$out.tar.gz" "$name"
