#!/bin/sh

# REPLACE with your PHP5 binary path (example: /usr/local/php5/bin/php )
#MAGE_PEAR_PHP_BIN="php"

PEAR_PATH="downloader/pearlib"

# initial setup
if test "x$1" = "xmage-setup"; then
    echo 'Running initial setup...'

    if test "x$2" != "x"; then
        MAGE_ROOT_DIR="$2"
    else
        MAGE_ROOT_DIR="`pwd`"
    fi

    MAGE_PEAR_ROOT_DIR="$MAGE_ROOT_DIR/$PEAR_PATH"

    $0 config-set bin_dir "$MAGE_PEAR_ROOT_DIR"
    $0 config-set doc_dir "$MAGE_PEAR_ROOT_DIR/docs"
    $0 config-set ext_dir "$MAGE_PEAR_ROOT_DIR/ext"
    $0 config-set php_dir "$MAGE_PEAR_ROOT_DIR/php"
    $0 config-set cache_dir "$MAGE_PEAR_ROOT_DIR/cache"
    $0 config-set data_dir "$MAGE_PEAR_ROOT_DIR/data"
    $0 config-set download_dir "$MAGE_PEAR_ROOT_DIR/download"
    $0 config-set temp_dir "$MAGE_PEAR_ROOT_DIR/temp"
    $0 config-set test_dir "$MAGE_PEAR_ROOT_DIR/tests"

    $0 config-set mage_dir "$MAGE_ROOT_DIR"
    $0 config-set mage_web_dir "$MAGE_ROOT_DIR"
    $0 config-set mage_etc_dir "$MAGE_ROOT_DIR/app/etc"
    $0 config-set mage_core_dir "$MAGE_ROOT_DIR/app/code/core"
    $0 config-set mage_community_dir "$MAGE_ROOT_DIR/app/code/community"
    $0 config-set mage_local_dir "$MAGE_ROOT_DIR/app/code/local"
    $0 config-set mage_design_dir "$MAGE_ROOT_DIR/app/design"
    $0 config-set mage_lib_dir "$MAGE_ROOT_DIR/lib"
    $0 config-set mage_media_dir "$MAGE_ROOT_DIR/media"
    $0 config-set mage_test_dir "$MAGE_ROOT_DIR/tests"
    $0 config-set mage_skin_dir "$MAGE_ROOT_DIR/skin"
    $0 config-set mage_locale_dir "$MAGE_ROOT_DIR/app/locale"

    $0 config-set preferred_state beta
    $0 config-set cache_ttl 60

    $0 channel-discover connect.magentocommerce.com/core
    $0 channel-discover connect.magentocommerce.com/community

    exit
fi

# check that mage pear was initialized
if test "x$1" != "xconfig-set" &&
  test "x$1" != "xconfig-get" &&
  test "x$1" != "xconfig-show" &&
  test "x$1" != "xchannel-discover" &&
  test "x`$0 config-get mage_dir`" = "x"; then
    echo 'Please initialize Magento PEAR installer by running:'
    echo "$0 mage-setup"
    exit;
fi

# find which PHP binary to use
if test "x$MAGE_PEAR_PHP_BIN" != "x"; then
  PHP="$MAGE_PEAR_PHP_BIN"
else
  PHP=php
fi

# get default pear dir of not set
if test "x$MAGE_PEAR_ROOT_DIR" = "x"; then
    MAGE_PEAR_ROOT_DIR="`pwd`/$PEAR_PATH"
fi

# look for the right pear include dir
if test "x$MAGE_PEAR_INSTALL_DIR" != "x"; then
  INCDIR=$MAGE_PEAR_INSTALL_DIR
  INCARG="-d include_path=$MAGE_PEAR_INSTALL_DIR"
else
  INCDIR="$MAGE_PEAR_ROOT_DIR/php"
  INCARG="-d include_path=$MAGE_PEAR_ROOT_DIR/php"
fi

# look for pear.ini file
if test "x$MAGE_PEAR_INI" != "x"; then
  PEAR_INI=$MAGE_PEAR_INI
else
  PEAR_INI="$MAGE_PEAR_ROOT_DIR/pear.ini"
fi

exec $PHP -C -q $INCARG -d output_buffering=1 -d variables_order=EGPCS \
    -d open_basedir="" -d safe_mode=0 -d register_argc_argv="On" \
    -d auto_prepend_file="" -d auto_append_file="" \
    $INCDIR/pearmage.php -c $PEAR_INI "$@"

