#!/usr/bin/env bash

# -------------------------------
display_help()
{
    echo "Script used to show latest versions of virtual environments. Needed to"
    echo "find out the version of the virtual environments already available in the grid."
    echo ""
    echo "-n: Number of lines to print, default 5"
    echo "-l: LXPLUS name, needed to find environment in grid. If not passed, will pick it up
    from the LXNAME environment variable" 
}
# -------------------------------
get_opts()
{
    NLINES=5
    while getopts :hf:n:l: option; do 
        case "${option}" in
            h)  
                display_help
                exit 0
                ;;  
            n)  NLINES=${OPTARG};;
            l)  LXNAME=${OPTARG};;
           \?)  echo "Invalid option: -${OPTARG}"
                display_help
                exit 1
                ;;  
            :)  echo "$0: Arguments needed"
                display_help
                exit 1
                ;;  
        esac
    done
}
# -------------------------------
check_env()
{
    which dirac-dms-user-lfns > /dev/null 2>&1
    if [[ $? -ne 0 ]];then
        echo "Dirac not available, run lb_dirac to be in the right environment"
        exit 1
    fi

    if [[ -z $LXNAME ]];then
        echo "No LXNAME found in the environment and no value passed with -l option"
        exit 1
    fi
}
# -------------------------------
print_latest()
{
    LFNPATH=/lhcb/user/${LXNAME:0:1}/$LXNAME/run3/venv
    FILENAME=dcheck.tar
    dirac-dms-user-lfns -w $FILENAME -b $LFNPATH > /dev/null 2>&1

    LFNLIST=lhcb-user-${LXNAME:0:1}-$LXNAME-run3-venv.lfns

    NLFN=$(cat $LFNLIST | wc -l)
    if [[ $NLFN -eq 0 ]];then
        echo "No LFNs for $FILENAME found in $LFNPATH"
        exit 1
    fi

    tail -n $NLINES $LFNLIST
    rm $LFNLIST
}
# -------------------------------
get_opts "$@"
check_env
print_latest

