#!/usr/bin/env bash
# Compiles src/agg/vk.comp and writes it as a C array to src/agg/vk_spv.h (the file the VULKAN=1 build includes: a build
# needs no shader compiler). Run it, and commit the result, after editing the shader:  make gpu-shaders
#   scripts/gen-aggvk-spv.sh            write the header
#   scripts/gen-aggvk-spv.sh --check    fail when the header is not what the shader gives with this glslc
set -euo pipefail
cd "$(dirname "$0")/.."

SRC=src/agg/vk.comp
OUT=src/agg/vk_spv.h
tool=$(command -v glslc || true)
[ -n "$tool" ] || { echo "gen-aggvk-spv: glslc (shaderc) is not installed" >&2; exit 2; }

tmp=$(mktemp -d "${TMPDIR:-/tmp}/sift-aggvk-spv.XXXXXX")
trap 'rm -rf "$tmp"' EXIT
glslc --target-env=vulkan1.0 -O -o "$tmp/agg.spv" "$SRC"

python3 - "$tmp/agg.spv" "$tmp/out.h" <<'EOF'
import struct, sys
data = open(sys.argv[1], "rb").read()
words = struct.unpack("<%dI" % (len(data) // 4), data)
lines = ["/*",
         " * agg/vk_spv.h - the SPIR-V of src/agg/vk.comp (glslc --target-env=vulkan1.0 -O), generated by scripts/gen-aggvk-spv.sh;",
         " * do not edit. Checked in so that a VULKAN=1 build needs no shader compiler.",
         " */",
         "#ifndef SIFT_AGGVK_SPV_H",
         "#define SIFT_AGGVK_SPV_H",
         "",
         "#include <stdint.h>",
         "",
         "static const uint32_t sift_vk_spv_agg[%d] = {" % len(words)]
for i in range(0, len(words), 8):
    lines.append("\t" + ", ".join("0x%08x" % w for w in words[i:i + 8]) + ",")
lines += ["};", "", "#endif\t\t\t\t\t\t\t/* SIFT_AGGVK_SPV_H */", ""]
open(sys.argv[2], "w").write("\n".join(lines))
EOF

if [ "${1:-}" = "--check" ]; then
	cmp -s "$tmp/out.h" "$OUT" || { echo "gen-aggvk-spv: $OUT differs from the shader (run scripts/gen-aggvk-spv.sh)" >&2; exit 1; }
	echo "gen-aggvk-spv: ok"
else
	cp "$tmp/out.h" "$OUT"
	echo "gen-aggvk-spv: wrote $OUT"
fi
