#!/usr/bin/env sh
# $Id$
#
# This script is a simple wrapper that will run Drush with the most appropriate
# php executable it can find.
#

# Get the absolute path of this executable
ORIGDIR=$(pwd)
SELF_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && SELF_PATH=$SELF_PATH/$(basename -- "$0")

# Resolve symlinks - this is the equivalent of "readlink -f", but also works with non-standard OS X readlink.
while [ -h $SELF_PATH ]; do
    # 1) cd to directory of the symlink
    # 2) cd to the directory of where the symlink points
    # 3) Get the pwd
    # 4) Append the basename
    DIR=$(dirname -- "$SELF_PATH")
    SYM=$(readlink $SELF_PATH)
    SELF_PATH=$(cd $DIR && cd $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
done
cd "$ORIGDIR"

# Build the path to drush.php.
SCRIPT_PATH=$(dirname $SELF_PATH)/drush.php
case $(uname -a) in
  CYGWIN*)
    SCRIPT_PATH=$(cygpath -w -a -- "$SCRIPT_PATH") ;;
esac

# If not exported and term is set determine and export the number of columns.
if [ -z $COLUMNS ] && [ -n "$TERM" ]; then
  # Note to cygwin users: if you are getting "tput: command not found", 
  # install the ncurses package to get it.
  export COLUMNS=$(tput cols)
fi

# Special case for *AMP installers, since they normally don't set themselves as the default cli php out of the box.
for php in /Applications/MAMP/bin/php5/bin/php /Applications/MAMP/bin/php5.2/bin/php /Applications/MAMP/bin/php5.3/bin/php /opt/lampp/bin/php /Applications/xampp/xamppfiles/bin/php /Applications/acquia-drupal/php/bin/php; do
  if [ -x $php ]; then
    exec $php $SCRIPT_PATH --php="$php" "$@"
  fi
done

# We check for a command line (cli) version of php, and if found use that.
which php-cli >/dev/null 2>&1
if [ "$?" = 0 ] ; then
  exec php-cli $SCRIPT_PATH --php="php-cli" "$@"
else
  # Alternatively we run with straight php, which works on most other systems.
  # The --php=`which php` is for Dreamhost, which behaves oddly.  See http://drupal.org/node/662926
  exec php $SCRIPT_PATH --php=`which php` "$@"
fi
