#!/bin/bash

name="_NAME_"
description='_DESCRIPTION_'
version='_VERSION_'
prefix=`dirname $0`/..
prefix=`readlink -f $prefix`
repodir=`readlink -f .`
port=8080
defaultport=$port
markup='textile'
escape_html='false'
silent=""
verbose=""
build="byte"

usage ()
{
echo "Usage: $0 [options] [working dir]
$description

Options:
  -p n             port to listening; default is $port
  -dp n            default port which will be used
                   for urls; default is $port
  -textile         set markup to textile; this is by default
  -polebrush       set markup to polebrush
  -html            set markup to pure html
  -escape-html     escape html among markup; does nothing with -html
  -native          run nativecode version instead of bytecode
  -h, --help       print this help and exit
  --version        print version and exit
  -s, --silent     silent mode (error messages go in
                   ${logdir}/errors.log only)
  -v, --verbose    verbose mode.
  -V, --veryverbose    very verbose mode (debug)
  -version         show version of program"

}

while true; do
  case "$1" in
    -version|--version) echo $version; shift;;
    -p)
      case "$2" in
        "") echo "Error: no port specified"; usage; exit 1;;
        *) port=$2; shift 2;;
      esac;;
    -dp)
      case "$2" in
        "") echo "Error: no default port specified"; usage; exit 1;;
        *) defaultport=$2; shift 2;;
      esac;;
    -textile) markup="textile"; shift;;
    -polebrush) markup="polebrush"; shift;;
    -html) markup="html"; shift;;
    -escape-html) escape_html="true"; shift;;
    -native|--native) build="native"; shift;;
    -h|--help) usage; exit 0;;
    -s|--silent) silent=" -s"; shift;;
    -v|--verbose) verbose=" -v"; shift;;
    -V|--veryverbose) verbose=" -V"; shift;;
    "") shift; break;;
    *) repodir=`readlink -f $1`; shift;;
  esac
done

logdir="_LOGDIR_/$port"
datadir="_DATADIR_/$port"
commandpipe="_COMMANDPIPE_"
config=$datadir/$name-standalone.xml
byte=$prefix/bin/${name}.byte
native=$prefix/bin/${name}.native

mkdir -p $logdir
cp -f $prefix/share/$name/$name-standalone.xml $config

sed "s|PREFIX|$prefix|g"           -i $config
sed "s/DEFAULTPORT/$defaultport/g" -i $config
sed "s/MARKUP_TYPE/$markup/g"      -i $config
sed "s/ESCAPE_HTML/$escape_html/g" -i $config
sed "s/PORT/$port/g"               -i $config
sed "s|REPODIR|$repodir|g"         -i $config
sed "s|LOGDIR|$logdir|g"           -i $config
sed "s|DATADIR|$datadir|g"         -i $config
sed "s|COMMANDPIPE|$commandpipe|g" -i $config

cd $prefix
if [ "$build" = "native" ]
  then $native $1 -c $config $silent$verbose
  else $byte $1 -c $config $silent$verbose
fi

