#!/bin/sh

# Image wasi-sdk paths
WASI_SDK='/opt/wasi-sdk'
WASI_SYSROOT="${WASI_SDK}/share/wasi-sysroot"
CLANG_SYSROOT="${WASI_SDK}/lib/clang/19"
export WASI_SDK WASI_SYSROOT CLANG_SYSROOT

# Ensure ${WASI_SDK}/bin is in ${PATH}
export PATH="${WASI_SDK}/bin:${PATH}"

# trim_spaces <...>
#
# replaces all whitespace in args with regular space.
trim_spaces() { echo "$@" | tr -s '[:space:]' ' '; }

# merge_archives <output> <archives...>
#
# merges all given 'archives' into 'output'.
merge_archives() {
    output=${1}; shift 1
    inputs=$( for input in ${@}; do echo "ADDLIB ${input}"; done )
    llvm-ar -M << EOF
CREATE ${output}
${inputs}
SAVE
END
EOF
}

[ -z $(cat /.once 2> /dev/null) ] && {
        echo 1 > /.once

        # Ensure vendor dir exists
        mkdir -p /vendor/include
        mkdir -p /vendor/lib

        # Insert a wasm-ld wrapping script that
        # drops unsupported arguments (soname, etc).
        mv ${WASI_SDK}/bin/wasm-ld ${WASI_SDK}/bin/wasm-ld.bin
        cat << 'EOF' > '/usr/bin/wasm-ld'
#!/bin/bash
new_args=()
ignore_next_arg=false
for var in "$@"; do
        case $var in
                '-I'*) ;;
                '-shared') ;;
                '-soname') ignore_next_arg=true ;;
                '--version-script') ignore_next_arg=true ;;
                *)
                        if [[ "$ignore_next_arg" == "true" ]]; then
                                ignore_next_arg=false
                        else
                                new_args+=($var)
                        fi
                ;;
        esac
done
exec wasm-ld.bin ${new_args[*]}
EOF
        chmod +x '/usr/bin/wasm-ld'
}

# Set toolchain binaries
export CC=$(which clang) \
       CXX=$(which clang++) \
       LD=$(which wasm-ld) \
       NM=$(which llvm-nm) \
       AR=$(which llvm-ar) \
       STRIP=$(which true) \
       RANLIB=$(which llvm-ranlib)

# Set CFLAGS,
# CXXFLAGS,
# LDFLAGS,
# WASMOPTFLAGS.
CFLAGS="
--sysroot=${WASI_SYSROOT}
--target=wasm32-wasi
-I/vendor/include
-I${WASI_SYSROOT}/include/wasm32-wasi
-flto=full -O3 -g0
-mllvm=-wasm-enable-sjlj
-mbulk-memory
-msimd128
-mnontrapping-fptoint
-msign-ext
-mmutable-globals
-mreference-types"
LDFLAGS="
-L/vendor/lib
-L${CLANG_SYSROOT}/lib/wasi
-lclang_rt.builtins-wasm32
-L${WASI_SYSROOT}/lib/wasm32-wasi
-lc -lc++
-lsetjmp"
WASMOPTFLAGS='
--debuginfo
--strip-dwarf
--strip-producers
--enable-simd
--enable-bulk-memory
--enable-nontrapping-float-to-int
--enable-mutable-globals
--enable-sign-ext
--enable-reference-types
--low-memory-unused'

# Export all flags with space trimmed.
export CFLAGS=$(trim_spaces $CFLAGS)
export CXXFLAGS=$(trim_spaces $CFLAGS)
export LDFLAGS=$(trim_spaces $LDFLAGS)
export WASMOPTFLAGS=$(trim_spaces $WASMOPTFLAGS)

# Export useful funcs.
export trim_spaces
