#!/bin/bash
# Bash replacement for Sources/ShaderCompiler/GenerateAll.ps1

get_program_names() {
    local shader_file="$1"
    local -n ref_array=$2
    while IFS= read -r line; do
        if [[ $line =~ ^[[:space:]]*(program|batched)[[:space:]]+([[:alnum:]_]+)[[:space:]]*\; ]]; then
            ref_array+=("${BASH_REMATCH[2]}")
        fi
    done < "$shader_file"
}

tool=./build-shadercompiler/ShaderCompiler
outDir=Sources/Shaders/Generated

${tool} --emit-types ${outDir}/ShaderCompilerTypes.h

generated_headers=()
jazz2Names=()
nCineNames=()
for f in Sources/Shaders/*.shader ; do
    fbase=$(basename "${f}")
    header=${fbase/.shader/.h}
    fout=${outDir}/${header}
    generated_headers+=(${header})

    if [[ "$fbase" =~ ^Default.* ]]; then
        ns='nCine::ShadersGen'
        get_program_names $f nCineNames
    else
        ns='Jazz2::ShadersGen'
        get_program_names $f jazz2Names
    fi

    ${tool} ${f} -o ${fout} -n ${ns}
done

${tool} --emit-sw-generated ${outDir}/SwGeneratedShaders.h Sources/Shaders/*.shader

echo '#pragma once' > ${outDir}/ShadersGen.h
for s in "${generated_headers[@]}"; do
    echo "#include \"${s}\"" >> ${outDir}/ShadersGen.h
done

cat << EOF >> ${outDir}/ShadersGen.h

#ifndef DOXYGEN_GENERATING_OUTPUT
namespace Jazz2::ShadersGen
{
	// All generated Jazz2 shader programs, sorted by name
	inline constexpr const ShaderCompiler::Program* AllPrograms[] = {
EOF

for name in "${jazz2Names[@]}"; do
    echo -e "\t\t&${name}," >> ${outDir}/ShadersGen.h
done

cat << EOF >> ${outDir}/ShadersGen.h
	};
}

namespace nCine::ShadersGen
{
	// All generated nCine default shader programs, sorted by name
	inline constexpr const ShaderCompiler::Program* AllPrograms[] = {
EOF

for name in "${nCineNames[@]}"; do
    echo -e "\t\t&${name}," >> ${outDir}/ShadersGen.h
done

cat << EOF >> ${outDir}/ShadersGen.h
	};
}
#endif
EOF
