#!/bin/bash

## These 3 lines are mandatory.
export PERLBREW_ROOT="/usr/share/profphd/prof/perl5"
export PERLBREW_HOME="/tmp/.perlbrew"

PERLBREW_PATH="/usr/bin/perlbrew"

PERL_BAD=5016
PERL_VER=$(perl -e 'print $]' | sed "s/\.//g" | awk '{ print substr( $0, 1, 4 ) }')

function echoerr() { echo "$@" 1>&2; }

function messageInstallPerlbrew() {
    echoerr ""
    echoerr "-----------------------------------------------------------------" 
    echoerr "You need to have perlbrew install perl v5.10.1 for use with prof."
    echoerr "Issue the commands using sudo:"
    echoerr "export PERLBREW_ROOT=${PERLBREW_ROOT}"
    echoerr "export PERLBREW_HOME=${PERLBREW_HOME}"
    echoerr "perlbrew init"
    echoerr "source ${PERLBREW_ROOT}/etc/bashrc"
    echoerr 'perlbrew install -j `nproc` --notest --noman perl-5.10.1'
    echoerr "----------------------------------------------------------------"
    echoerr ""
}

function messagePerl2New() {
    echoerr ""
    echoerr "-----------------------------------------------------------------------------"
    echoerr "Your perl version must be less than v5.16 in order for this program to work!"
    echoerr "Please install a compatible version of Perl < v5.16, or check out Perlbrew"
    echoerr "if your OS does not have an compatible perl package avaialble."
    echoerr "-----------------------------------------------------------------------------"
    echoerr ""
}

if [ ${PERL_VER} -ge ${PERL_BAD} ]
then
    ## Do stuff with perl 5.10.1 if perlbrew installed
    if [ -x ${PERLBREW_PATH} ]
    then
        if [ -e "${PERLBREW_ROOT}/etc/bashrc" ]
        then
            source ${PERLBREW_ROOT}/etc/bashrc
        else
            messageInstallPerlbrew
            exit 255
        fi
        # Notice, with the bash integeration, the statement perlbrew use 5.14.1 actually 
        #invokes the perlbrew bash function instead of the command perlbrew
        perlbrew use 5.10.1
        if [ ${?} -gt 0 ]
        then
            messageInstallPerlbrew
            exit 255
        fi
    else
        # Need earlier version of perl installed
        messagePerl2New
        exit 255
    fi
fi

# Execute prof
perl /usr/share/profphd/prof/prof.pl "$@"
exit $?
