#!/bin/sh

#Shamelessly "inspired" by pear.

#first find which PHP binary to use
if test "x$PHP_PEAR_PHP_BIN" != "x"; then
  PHP="$PHP_PEAR_PHP_BIN"
else
  if test "@php_bin@" = '@'php_bin'@'; then
    #pear installer replacement task has not processed this file
    PHP=php 
  else
    #pear installer will substitute the propert location of php here
    PHP="@php_bin@"
  fi
fi

#find all parental projects and add them to the include_path

PROJECT_PATH=""
DIR=`pwd`

while test "$DIR" != "/"; do
    if test -e "$DIR/.wactproj"; then
        if test "$PROJECT_PATH" != "x"; then
            PROJECT_PATH=$DIR
        else
            PROJECT_PATH="$PROJECTPATH:$DIR"
        fi
    fi
    DIR=`dirname $DIR`
done

#get it done.

exec $PHP -- "$@" <<EOF
<?php 

    // set the include path from the shell
    if ("$PROJECT_PATH" != "") {
        set_include_path("$PROJECT_PATH:" . get_include_path());
    }

    if (is_resource(\$fh = @fopen('Console/Getopt.php', 'r', true))) {
        fclose(\$fh);
        unset(\$fh);
        require_once 'Console/Getopt.php';
    } else {
?>
Cannot locate the PEAR Console_Getopt package.  Please install this to your 
include_path for cli support.
<?php
        exit;
    }

    // Let the include path sort out the proper command to execute.

    if (is_resource(\$fh = @fopen('Wact/Tool/Cli/dispatcher.php', 'r', true))) {
        fclose(\$fh);
        unset(\$fh);

        require_once 'Wact/Loader.inc.php';
        Wact_Loader::setupWact();

        require_once 'Wact/Tool/Cli/dispatcher.php'; 

        \$dispatcher = new Wact_Tool_Cli_Dispatcher();
        \$dispatcher->run(Console_Getopt::readPHPArgv());

    } else {
?>
Cannot locate the php portion of the wact command.  Please add wact to your 
include_path or change your current directory to be inside the wact project
directory.
<?php
    }
?>
EOF
