# to use these routines:
#
#    1) copy this file to somewhere (e.g. ~/.beaglerc).
#    2) add the following line to your .bashrc:
#        source ~/.beaglerc
#

if [[ -f $HOME/.beagle/init ]]; then
    source $HOME/.beagle/init
fi

__beagle_reinit () {
    echo '# DO NOT EDIT THIS FILE' > $HOME/.beagle/init
    echo "export BEAGLE_NAME=$1" >> $HOME/.beagle/init
    source $HOME/.beagle/init
}

beagle () {
    local exit_status
    case $1 in
        (which)
            if [[ "$BEAGLE_ROOT" != "" ]]; then
                echo $BEAGLE_ROOT
            else
                if [[ "$BEAGLE_NAME" != "" ]]; then
                    echo $BEAGLE_NAME
                else
                    echo "global"
                fi
            fi
            ;;

        (use)
            if [[ "$2" = "global" ]]; then
                export BEAGLE_NAME=
                export BEAGLE_ROOT=
                echo 'switched to "global" in current session.'
            else
                exists=`beagle exists $2`
                if [[ $exists == "true" ]]; then
                    export BEAGLE_NAME="$2"
                    echo "switched to \"$2\" in current session."
                else
                    echo "no such name \"$2\"."
                fi
            fi
            ;;

        (switch)
            if [[ ! -d $HOME/.beagle ]]; then
                mkdir -p $HOME/.beagle
            fi

            if [[ "$2" = "global" ]]; then
                __beagle_reinit ''
                echo 'switched to "global".'
            else
                exists=`beagle exists $2`
                if [[ $exists == "true" ]]; then
                    __beagle_reinit "$2" 
                    echo "switched to \"$2\"."
                else
                    echo "no such name \"$2\"."
                fi
            fi
            ;;
        (*)
            command beagle "$@"
            exit_status=$?
            ;;
    esac
}

