#!/bin/bash

__filename="$(readlink -f "$0")"
pathstr="$(cd "$(dirname "$__filename")" && pwd)"

trap 'kill $(jobs -p) ; exit 1' INT

# Sometimes, npm i -g target directory is missing from module search path.
# So set this script module path as current path.
pi=${pathstr##*node_modules}
pi=$((${#pathstr} - ${#pi}))
if [ $pi -eq 0 ]; then
  pathstr=$pathstr/node_modules
else
  pathstr=${pathstr:0:$pi}
fi

# Also, find picogw module from the globally installed picogw location.
sysDir=$(npm root -g | tr -d '\n')

# Check if picogw is installed globally
if [ -z "$sysDir" ]; then
  echo -e "\e[31mPlease install PicoGW globally!\e[0m"
  exit 1
fi

while true; do
  # Run picogw
  cd $pathstr
  node "$sysDir/picogw/main.js" "${@:1:($#)}"
  exit_code=$?
  if [ "$exit_code" -eq 99 ]; then
    echo "PicoGW was exited without rebooting."
    break
  fi
done
