#!/bin/env sh
# townengine tooling interface

set -e

exe="$(basename $PWD)"
toolpath="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
export TWNROOT=$(realpath "$toolpath"/../)

case "$1" in
    build    ) "$toolpath"/twnbuild "${@:2}"
               ;;

    run      ) $0 build "${@:2}"
               if [[ "$*" == *"--target=web"* ]]; then
                   if [ "$OS" = "Windows_NT" ]; then
                       explorer "http://0.0.0.0:8000/$exe.html" & python3 -m http.server
                   else
                       xdg-open "http://0.0.0.0:8000/$exe.html" & python3 -m http.server
                   fi
               else
                   ./$exe
               fi
               ;;

    gdb      ) unset DEBUGINFOD_URLS
               $0 build --debug && gdb --se=libgame.so -ex run --args "$(basename $PWD)" --no-sanity-timer "${@:2}"
               ;;

    init     ) cp -r "$TWNROOT/apps/templates/$2" "$3"
               ln -s "$TWNROOT/bin/twn" "$3/twn"
               ;;

    apitrace ) case "$2" in
        take ) export ASAN_OPTIONS=verify_asan_link_order=0
               export LD_PRELOAD="/usr/lib/libubsan.so /usr/lib/apitrace/wrappers/glxtrace.so $LD_PRELOAD"
               ./$exe "${@:3}"
               ;;

        show ) traces=( $exe.*.trace )
               trace=${traces[-1]}
               if [ "$trace" = "$exe.*.trace" ]; then
                   trace="$exe.trace"
               fi
               qapitrace ${trace}
               ;;
    esac
               ;;

    api-gen  ) "$toolpath"/gen_api_header.sh
               ;;

    wiki     ) if [ "$OS" = "Windows_NT" ]; then
                   explorer "file://""$(cygpath -w "$(command realpath $TWNROOT/docs/wiki/index.html)")"
               else
                   xdg-open "file://$TWNROOT/docs/wiki/index.html"
               fi
               ;;

    devcompl ) (cd "$TWNROOT" && "$toolpath"/twnbuild "--build_dir=$TWNROOT/build" "${@:2}")
               ;;

    *        ) echo "Unknown command."
               ;;
esac