#!/bin/bash

set_environment () {

  echo " Set environment variables"

  # Here, define your installation paths, versions etc.
  PY_INSTALLPATH="$1"
  PY_VERSION="$2"
  DIRE_VERSION="$3"

}

run () {

  workd=$(pwd)

  if [[ "$PY_VERSION" -lt "8212" ]] ; then
    echo "Sorry, DIRE is only compatible with Pythia version after 8.212"
    echo "Exit isntallation"
    exit 0
  fi

  if [[ "$DIRE_VERSION" -eq "-1" ]] ; then
    if [[ "$PY_VERSION" -eq "8212" ]] ; then
      DIRE_VERSION="0.900";
    elif [[ "$PY_VERSION" -gt "8212" && "$PY_VERSION" -lt "8226" ]] ; then
      DIRE_VERSION="1.500";
    elif [[ "$PY_VERSION" -gt "8225" ]] ; then
      DIRE_VERSION="current";
    fi
  else
   if [[ "$PY_VERSION" -eq "8212" && "$DIRE_VERSION" -ne "0.900" ]]; then
    DIRE_VERSION="0.900";
    echo "Incompatible DIRE version. Using DIRE v $DIRE_VERSION instead"
   elif [[ "$PY_VERSION" -gt "8212" && "$PY_VERSION" -lt "8226" && "$DIRE_VERSION" -lt "0.900" ]]; then
    DIRE_VERSION="1.500";
    echo "Incompatible DIRE version. Using DIRE v $DIRE_VERSION instead"
   elif [[ "$PY_VERSION" -gt "8225" && "$DIRE_VERSION" -lt "2.000" ]]; then
    DIRE_VERSION="current";
    echo "Incompatible DIRE version. Using DIRE v $DIRE_VERSION instead"
   fi
  fi

  cd $PY_INSTALLPATH

  echo " Download DIRE version $DIRE_VERSION"
  wget http://www.hepforge.org/archive/direforpythia/DIRE-${DIRE_VERSION}.tar.gz

  echo " Unpack DIRE"
  tar xvzf DIRE-${DIRE_VERSION}.tar.gz

  echo " Copy DIRE to PYTHIA8 directory"
  cp -r DIRE-${DIRE_VERSION} $PY_INSTALLPATH/pythia${PY_VERSION}/examples/DIRE
  cp -r DIRE-${DIRE_VERSION} $PY_INSTALLPATH/share/Pythia8/examples/DIRE

  echo " Compile DIRE example programs"
  cd $PY_INSTALLPATH/pythia${PY_VERSION}/examples/DIRE
  ls -1 dire*.cc | while read line
  do
    make "$(echo "$line" | sed "s,\.cc,,g")"
  done
  cd $PY_INSTALLPATH/share/Pythia8/examples/DIRE
  ls -1 dire*.cc | while read line
  do
    make "$(echo "$line" | sed "s,\.cc,,g")"
  done

  echo " Finished DIRE installation"
  cd $workd

}

set_environment "$@"
run "$@"
