#!/usr/bin/env bash

# ------------------------------------------------------------------
display_help()
{
    echo "Utility needed to setup shell environment where to use post_ap scripts"
    echo ""
    echo "-h: Print this help"
}
# ------------------------------------------------------------------
get_opts()
{
    TEST=1
    while getopts :hf:u:c: option; do 
        case "${option}" in
            h)  
                display_help
                exit 0
                ;;  
           \?)  echo "Invalid option: -${OPTARG}"
                display_help
                exit 1
                ;;  
            :)  echo "$0: Arguments needed"
                display_help
                exit 1
                ;;  
        esac
    done
}
# ------------------------------------------------------------------
make_rcfile()
{
    export RCFILE=/tmp/bash_dirac
    touch $RCFILE

    echo "#!/usr/bin/env bash"                    >> $RCFILE
    echo ""                                       >> $RCFILE
    echo "export PS1='\u@\h\$ '"                  >> $RCFILE
    echo "export PATH+=:$POSTAP_PATH"             >> $RCFILE
    echo "export VENVS=$VENVS"                    >> $RCFILE
    echo "export LXNAME=$LXNAME"                  >> $RCFILE
    echo "# This will be your username in LXPLUS" >> $RCFILE
}
# ------------------------------------------------------------------
initialize()
{
    if [[ -z $POSTAP_PATH ]];then
        echo "POSTAP_PATH (micromamba for the environment with the code) not set"
        exit 1
    fi

    if [[ -z $VENVS ]];then
        echo "VENVS (path where virtual environment tarballs will be saved) not set"
        exit 1
    fi

    if [[ -z $LXNAME ]];then
        echo "LXNAME (user's name in LXPLUS) not set"
        exit 1
    fi
}
# ------------------------------------------------------------------
lb_dirac()
{
    # Will create a shell with dirac and some basic environment specified by rc file 
    
    which lb-dirac > /dev/null 2>&1

    if [[ $? -ne 0 ]];then
        echo "Cannot find lb-dirac, LHCb software not set, setting it"
        lhcb_env
    fi

    if [[ ! -f $RCFILE ]];then
        echo "Cannot find $RCFILE"
        exit 1
    fi

    lb-dirac bash -c "source $RCFILE && exec bash --norc"
}
# ------------------------------------------------------------------
lhcb_env()
{
    # This function will setup the LHCb environment

    LBENV_PATH=/cvmfs/lhcb.cern.ch/lib/LbEnv

    if [[ ! -f $LBENV_PATH ]]; then
        echo "Cannot find $LBENV_PATH"
        kill INT $$
    fi

    . $LBENV_PATH
}
# ------------------------------------------------------------------
get_opts "$@"
initialize
make_rcfile
lb_dirac
