#!/usr/bin/env bash
currdir=`dirname $0`
currdir=$(cd "$currdir" && pwd)

# Support qtlua, if it is available
LUA=$currdir/luajit
ls $LUA >/dev/null 2>&1
if [ $? == 1 ]; then
    LUA=$currdir/lua
fi

# Pipe for stdout
IO_STDO=$(mktemp -t itorch.stdout.XXXXXXXXXX)
rm $IO_STDO
if [ $(uname) == "Darwin" ]; then
    mkfifo $IO_STDO
else
    touch $IO_STDO
fi

# Process 1 writes the port number to communicate to this file
# Process 2 reades from this file and binds to that port
IO_PORTNUM=$(mktemp -t itorch.PORTNUM.XXXXXXXXXX)
"$LUA" -e "arg={'$1','$IO_PORTNUM'};require 'itorch.main'" 2>&1 >$IO_STDO &
"$LUA" -e "arg={'$1','$IO_STDO','$IO_PORTNUM'};require 'itorch.IOHandler'"

# temporary files $IO_STDO and $IO_PORTNUM are cleaned up on shutdown of itorch.IOHandler
