#!/bin/sh

# Copyright (c) 2007-2008 Fabien Tassin <fta@sofaraway.org>
# Description: Prism helper
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

PRISM=/usr/bin/prism-bin
WEBRUNNER=/usr/share/prism
WEBAPPDIR=/usr/share/prism/apps

if [ "$1" = "-d" ] ; then
  DEBUG="-console -jsconsole"
  shift
fi

if [ "Z$1" != Z ] && [ "`echo $1 | sed -e 's/.*\.//'`" = "webapp" ] ; then
  WEBAPP=`echo $1 | sed -e 's,^file://,,'`
  FILE=$WEBAPP
else
  APPNAME=`basename $0 | sed -e 's/\.sh$//; s/prism-//'`
  if [ -f $WEBAPPDIR/$APPNAME.webapp ] ; then
    FILE=$WEBAPPDIR/$APPNAME.webapp
  else
    ARGS=$@
  fi
fi

if [ "Z$FILE" != "Z" ] ; then
  # If this webapp has already been extracted, run it by its id rather than
  # by its filename that unpacks it at each run.
  # It's important to preserve the json file for window size and position.
  ARGS="-webapp $FILE"
  if [ -f $FILE ] ; then
    ID=`unzip -p $FILE webapp.ini | grep ^id= | cut -d= -f2 | tr -d '\r'`
    DIR=$HOME/.webapps/$ID
    if [ -d $DIR ] ; then # The webapp already exists.
      # Check for the png icon.
      WNAME=`grep -E '^icon=' $DIR/webapp.ini | cut -d= -f2 | tr -d '\r'`
      if [ ! -f $DIR/icons/default/$WNAME.png ] ; then
        ( cd $DIR/icons/default ; unzip $FILE $WNAME.png )
      fi
      ARGS="-webapp $ID"
      # Check for an override.ini file
      if [ ! -f $DIR/override.ini ] ; then
        ANAME=`grep -E '^name=' $DIR/webapp.ini | cut -d= -f2 | tr -d '\r'`
	if [ "Z$ANAME" != Z ] ; then
          printf "[App]\nVendor=Prism\nName=$ANAME" > $DIR/override.ini
          ARGS="-override $DIR/override.ini $ARGS"
	else
          # Add missing 'name' based on 'id'
          ANAME=`echo $ID | sed -e 's/@.*//'`
          echo "name=$ANAME" >> $DIR/webapp.ini
	  ARGS="-no-remote $ARGS"
        fi
      else
        ARGS="-override $DIR/override.ini $ARGS"
      fi
    fi
  else
    echo "Error: can't find $FILE"
    exit 1
  fi
fi

exec $PRISM $DEBUG $ARGS
