#!/bin/sh
# This starts gowrite2
#
# This script uses same GOWrite instance for all files.
# This way of starting is preferable, as currently only one process can access game database at once.
# 
# Script is somewhat hack. Problem seems to be that named pipe as standard input for java process 
# does not behave nicely. If someone has better solution, I would be happy.
#
# .gowrite/cmd pipe is used to feed commands to gowrite2; process id is stored in .gowrite/pid
#
# 05-02-2009: Added pid check to prevent deadlock when gowrite has died, but .gowrite/cmd exists
# 18-04-2009: Added several quotes, corrected test and added .gowrite directory creation; few comments added
# 26-03-2010: Includes all jar files in lib directory into classpath automatically.

# If you want to start gowrite with specific java version, set $GOWRITE_JAVA to point to java executable
jcmd=java
if [ "$GOWRITE_JAVA" != "" ]; then
  jcmd="$GOWRITE_JAVA"
fi

base="${0%/*}"

# Configuration directory needed for gowrite start
if [ ! -d ~/.gowrite ]; then
  mkdir ~/.gowrite
fi

# Start gowrite, if it is not already running
if [ ! -p ~/.gowrite/cmd ] || [ ! -f ~/.gowrite/pid ] || [ ! -d /proc/`cat ~/.gowrite/pid` ]
then
  echo starting GO Write 2...
  # clean up any remaining variables from past invocations.
  if [ -a ~/.gowrite/pid ]; then
    rm ~/.gowrite/pid
  fi
  if [ -a ~/.gowrite/cmd ]; then
    rm ~/.gowrite/cmd
  fi
  mknod -m 700 ~/.gowrite/cmd p
  {
    {
      # This is cludge (waiting for data does not work), but what is better way?
      while [ -p ~/.gowrite/cmd ]
        do
          while read cmd; do
            echo "$cmd"
          done
        sleep 1
        done
    } <~/.gowrite/cmd | {
      # Start gowrite, no need to pass files to open now.
      base="${0%/*}"
      cp="$base/GOWrite.jar:$base/GOWriteHelp.jar"
      cp="$cp:$base/lib/jh.jar"
      cp="$cp:$base/lib/swing-layout-1.0.3.jar"
      cp="$cp:$base/lib/h2.jar"
      for libs in $(find "$base/lib/" -name "GOWrite*.jar")
      do
        cp="$cp:$libs"
      done
      trap 'rm ~/.gowrite/cmd; exit' INT TERM EXIT 
      "$jcmd" -Dgowrite.root="$base" -Xmx400m -cp "$cp" GOWrite2 -waitfiles
      rm ~/.gowrite/cmd
      rm ~/.gowrite/pid
    }
  } >/dev/null 2>&1 &
  # save PID for testing process status
  PID=$!
  echo $PID >~/.gowrite/pid
fi

#   use fifo to instruct gowrite to open files. 
echo "-workdir" >>~/.gowrite/cmd
pwd >>~/.gowrite/cmd
echo "-open" >>~/.gowrite/cmd
for param in "$@"
  do
#   Some environments do not parse desktop file properly
    if [ "$param" != "%F" ]; then 
      echo "$param" >>~/.gowrite/cmd
    fi
  done
echo "-endopen" >>~/.gowrite/cmd
