#!/bin/bash

###########################################################
## Copyright (c) 2002-2024 Alexey Kuryakin daqgroup@mail.ru
###########################################################

#####################################################
# The script to prepare environment for launch ROOT.
#####################################################

########################
# script identification.
########################
readonly startupdir="$(pwd -LP)";
readonly scriptfile="${BASH_SOURCE[0]}";
readonly scriptname="$(basename $scriptfile)";
readonly scriptbase="$(basename $scriptfile .sh)";
readonly scripthome="$(dirname  $scriptfile)";
readonly scriptFILE="$(realpath $scriptfile)";
readonly scriptHOME="$(dirname  $scriptFILE)";

function fatal(){
 echo -ne "\n$2\n\n";
 exit $1;
};

function print_usage(){
 echo "$scriptname version 1.0";
 echo "Copyright (c) 2024 Alexey Kuryakin daqgroup@mail.ru";
 echo "Prepare root (CERN) environment & run command line.";
 echo "Usage: $scriptname [root [arg] | cmnd [arg] ]";
 echo " root [arg]  - run root with arguments [arg]";
 echo " cmnd [arg]  - run command (cmnd) with arguments [arg]";
 echo "Examples:";
 echo " $scriptname env | sort";
 echo " $scriptname root test.root";
 echo " $scriptname printenv ROOTSYS";
 echo " $scriptname '\$ROOTSYS/bin/root'";
};

readonly rootdir="/opt/daqgroup/share/root";
readonly rootexe="$rootdir/bin/root";

if pushd $rootdir >/dev/null 2>&1; then
 source bin/thisroot.sh;
else
 fatal 1 "Error: could not cd $rootdir";
fi;
popd >/dev/null 2>&1;

function eval_exec(){
 eval exec "$@";
};

###############
# main function
###############
function main(){
 if [ -z "$ROOTSYS" ]; then
  fatal 1 "Error: ROOTSYS is not set.\nPlease (re)install package 'daqgroup-root'.";
 fi;
 if [ -x "$ROOTSYS/bin/root" ]; then
  case $1 in
   '')   print_usage; return 0; ;;
   root) shift; exec $ROOTSYS/bin/root "$@"; ;;
   *)    eval_exec "$@"; ;;
  esac;
 else
  fatal 1 "Error: ROOT installation wrong.\nPlease install package 'daqgroup-root'.";
 fi;
};

main "$@";

##############
## END OF FILE
##############
