#!/usr/bin/env zsh

[[ ! -z "$MESON_SOURCE_ROOT" ]] && {
	cd "$MESON_SOURCE_ROOT"
	cd ..
}

[[ -d src/lua ]] || {
	print "error - directory not found: src/lua"
	return 1
}

pwd=`pwd`
dst=${pwd}/src/lualibs_detected.c
opts="${1}"
# script to take all extensions in src/lua and embed them inside
# zenroom as strings

compile_flag=""
[[ "$opts" == "compile" ]] && compile_flag="#define LUA_COMPILED 1"

cat <<EOF > ${dst}
// This file is generated by running build/embed-lualibs
#include <lua.h>
#include <lua_functions.h>

${compile_flag}

#ifdef __EMSCRIPTEN__
const unsigned int fakelen = 0;
#else
EOF
libs=`find src/lua -type f -name '*.lua'`

# emscripten doesn't supports embedding this way
# will use --preload-file instead

typeset -A emptyarray=()
extarray=()
c=0
for i in ${(f)libs}; do
    p=`basename $i`
    n=${p[(ws:.:)1]}
    f="lualib_${n}.c"
    print "+ $i $opts"
	tmp=`mktemp -d`
	if [[ "$opts" = "compile" ]]; then
		luac5.3 -o ${tmp}/${n} $i
	else
		cp $i ${tmp}/${n}
	fi
	pushd $tmp
	print         >>  ${dst}
	print "// $i" >>  ${dst}
	xxd -i ${n}   >>  ${dst}
	if [[ "`uname -s`" =~ "Linux" ]]; then
	   sed -i 's/^unsigned/const unsigned/' ${dst}
        else
	   sed -e 's/^unsigned/const unsigned/' -i '' "${dst}"
	fi
	print         >>  ${dst}
	popd
	rm -rf $tmp
	ext="{\"${n}\", &${n}_len, (const char *)${n}},"
	extarray+=($ext)
	emptyarray+=($ext "{\"${n}\", &fakelen, \"/$p\"},")
	c=$(( c + 1 ))
done

cat <<EOF >> ${dst}
#endif // __EMSCRIPTEN__

zen_extension_t zen_extensions[] = {
EOF
for i in $extarray; do
	cat <<EOF >> ${dst}
#ifndef __EMSCRIPTEN__
$i
#else
${emptyarray[$i]}
#endif
EOF
done
cat <<EOF >> ${dst}
    { NULL, NULL, NULL }
};
EOF
