#!/bin/bash
# -*- coding: utf-8 mode: sh -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
source "$(dirname -- "$0")/../load.sh" || exit 1

owd="$(pwd)"
PROJDIR=
while true; do
    cwd="$(pwd)"
    if [ -f .runphp.conf ]; then
        PROJDIR="$cwd"
        break
    elif [ -f composer.json ]; then
        PROJDIR="$cwd"
        break
    fi
    if [ "$cwd" == "$HOME" -o "$cwd" == / ]; then
        cd "$owd"
        break
    fi
    cd ..
done

if [ -z "$PROJDIR" ]; then
    # s'il n'y a pas de projet, --bs est l'action par défaut
    [ $# -gt 0 ] || set -- --bs --ue
elif [ "$MYNAME" == composer ]; then
    set -- composer "$@"
else
    case "$1" in
    *.php|*.phar) set -- php "$@";;
    esac
fi

if [ -n "$PROJDIR" ]; then
    export RUNPHP_STANDALONE=
    RUNPHP=; DIST=; REGISTRY=
    if [ -f "$PROJDIR/.runphp.conf" ]; then
        source "$PROJDIR/.runphp.conf"
        [ -n "$RUNPHP" ] && exec "$PROJDIR/$RUNPHP" "$@"
    elif [ -f "$PROJDIR/sbin/runphp" ]; then
        exec "$PROJDIR/sbin/runphp" "$@"
    elif [ -f "$PROJDIR/runphp" ]; then
        exec "$PROJDIR/runphp" "$@"
    fi
fi

export RUNPHP_STANDALONE="$NULIBDIR"
export RUNPHP_PROJDIR="$PROJDIR"
export RUNPHP_REGISTRY="$REGISTRY"
export RUNPHP_DIST="$DIST"
exec "$MYDIR/../runphp/runphp" "$@"