#!/bin/sh
# usage: jsh <function> [arg1] [arg2] ...
#         
# 'jsh prompt question answer' executes: js prompt('question','answer') )

source /etc/profile.sh

to_js(){
  printf "%s(" "$1"
  shift
  for arg in "$@"; do
    case "$arg" in
      (*[\.0-9]*) 
        printf '%s,' "$arg"
        ;;
      (*)
	printf '"%s",' "$arg"
        ;;
    esac
  done
  printf ")\n"
}

# run argument as js
test -z "$1" || {
  func=$(to_js "$@")
  func=${func/,)/)}
  js "return $func"
  hook "$@"
  exit 0
}

# otherwise start repl
echo "jsh> JavaScript [browser] runtime"
echo "jsh> type 'exit' or CTRL-C to quit"
echo "jsh> HINT: to run alert('foo') outside this REPL, run 'jsh alert foo'"
echo "jsh>"
while true; do
  echo -n -e "\n$(printf "\033[0m")jsh> $(printf "\033[0m")"
  read line
  test "$line" = exit && exit
  js "$line"
done