#!/bin/bash

#make sure we're being sourced 
if [[ "$0" =~ "moainit" ]]; then
    echo "Please *source* this file, run:"
    echo ". {PATH/}moainit.sh"
    echo "(note the dot!!)"
    exit -1;
fi

#few shortcuts
alias msp='moa set process'

#Set environment variables for moa
export MOABASE=`dirname $(dirname $(cd ${BASH_ARGV%/*} && echo $PWD/${BASH_ARGV##*/}))`
export PATH=$MOABASE/bin:$PATH
export PYTHONPATH=$MOABASE/lib/python:$PYTHONPATH
source $MOABASE/etc/bash_completion.d/moa 

###
### Moa prompt stuff!
alias moa_prompt_off='unset MOA_PROMPT'
alias moa_prompt_on='export MOA_PROMPT=yes'
if [[ ! "$PROMPT_COMMAND" =~ "_moa_prompt" ]]
then
    export PROMPT_COMMAND="_moa_prompt;$PROMPT_COMMAND"
fi

function _moa_prompt {
    
    #Get the last command
    #based on:
    #http://stackoverflow.com/questions/945288/...
    #     ...saving-current-directory-to-bash-history

    local lc=$(history 1)
    lc="${lc# *[0-9]*  }"
    
	#save the last command to a user specific location
    if [[ ! -d '~/.config/moa' ]]
    then
        mkdir -p ~/.config/moa
    fi
    echo $lc > ~/.config/moa/last.command

    [[ -d '.moa' ]] || return 0

	#and add it to the local history if this is a mob job
    touch .moa/local_bash_history
    if [[ -w '.moa/local_bash_history' ]]
    then
	echo $lc >> .moa/local_bash_history 2>/dev/null || true
    fi

    if [[ "$MOA_PROMPT" ]]
    then
        moaprompt
    fi
}
