#!/usr/bin/env bash
# Compile Vulkan GLSL shaders to SPIR-V and update the C++ headers used by SDL3GPUShader.
# Required: glslc (from Vulkan SDK or: brew install glslang / apt install glslang-tools)
#
# Run from the project root:  tools/shaders/compile_spirv.sh

set -e

SHADERS_DIR="data/shaders"
HEADERS_DIR="source/core/rendering/sdl3gpu"

if ! command -v glslc &> /dev/null; then
    echo "ERROR: glslc not found. Install Vulkan SDK or run:"
    echo "  macOS:  brew install glslang"
    echo "  Linux:  sudo apt install glslang-tools"
    exit 1
fi

echo "Compiling SPIR-V shaders..."

glslc "${SHADERS_DIR}/postfx.vert" -o /tmp/postfx.vert.spv
glslc "${SHADERS_DIR}/postfx.frag" -o /tmp/postfx.frag.spv
glslc "${SHADERS_DIR}/upscale.frag" -o /tmp/upscale.frag.spv
glslc "${SHADERS_DIR}/downscale.frag" -o /tmp/downscale.frag.spv

echo "Generating C++ headers..."

xxd -i /tmp/postfx.vert.spv | \
    sed 's/unsigned char .*postfx_vert_spv\[\]/static const uint8_t kpostfx_vert_spv[]/' | \
    sed 's/unsigned int .*postfx_vert_spv_len/static const size_t kpostfx_vert_spv_size/' \
    > "${HEADERS_DIR}/postfx_vert_spv.h"

xxd -i /tmp/postfx.frag.spv | \
    sed 's/unsigned char .*postfx_frag_spv\[\]/static const uint8_t kpostfx_frag_spv[]/' | \
    sed 's/unsigned int .*postfx_frag_spv_len/static const size_t kpostfx_frag_spv_size/' \
    > "${HEADERS_DIR}/postfx_frag_spv.h"

xxd -i /tmp/upscale.frag.spv | \
    sed 's/unsigned char .*upscale_frag_spv\[\]/static const uint8_t kupscale_frag_spv[]/' | \
    sed 's/unsigned int .*upscale_frag_spv_len/static const size_t kupscale_frag_spv_size/' \
    > "${HEADERS_DIR}/upscale_frag_spv.h"

xxd -i /tmp/downscale.frag.spv | \
    sed 's/unsigned char .*downscale_frag_spv\[\]/static const uint8_t kdownscale_frag_spv[]/' | \
    sed 's/unsigned int .*downscale_frag_spv_len/static const size_t kdownscale_frag_spv_size/' \
    > "${HEADERS_DIR}/downscale_frag_spv.h"

# Prepend required includes to the headers
for f in "${HEADERS_DIR}/postfx_vert_spv.h" "${HEADERS_DIR}/postfx_frag_spv.h" "${HEADERS_DIR}/upscale_frag_spv.h" "${HEADERS_DIR}/downscale_frag_spv.h"; do
    echo -e "#pragma once\n#include <cstdint>\n#include <cstddef>\n$(cat "$f")" > "$f"
done

echo "Done. Headers updated in ${HEADERS_DIR}/"
echo "  postfx_vert_spv.h"
echo "  postfx_frag_spv.h"
echo "  upscale_frag_spv.h"
echo "  downscale_frag_spv.h"
echo "Rebuild the project to use the new shaders."
