#!/bin/bash

# This script requires an apt dependency: libxerces-c-dev

GEANT4_VERSION=10.7.3
GEANT4_DOWNLOAD_URL=https://github.com/Geant4/geant4/archive/refs/tags/v${GEANT4_VERSION}.zip
GEANT4_DIRECTORY=/opt/geant4/${GEANT4_VERSION}
GEANT4_BUILD_DIRECTORY=${GEANT4_DIRECTORY}/build
GEANT4_INSTALL_DIRECTORY=${GEANT4_DIRECTORY}/install
GEANT4_SRC_DIRECTORY=${GEANT4_DIRECTORY}/src
GEANT4_TMP_DIRECTORY=${GEANT4_DIRECTORY}/tmp

# Create the necessary directories
mkdir -p ${GEANT4_DIRECTORY}
mkdir -p ${GEANT4_BUILD_DIRECTORY}
mkdir -p ${GEANT4_INSTALL_DIRECTORY}
mkdir -p ${GEANT4_TMP_DIRECTORY}

# fetch the source...
wget ${GEANT4_DOWNLOAD_URL} -O ${GEANT4_TMP_DIRECTORY}/v${GEANT4_VERSION}.zip

if [ ! -f "${GEANT4_TMP_DIRECTORY}/v${GEANT4_VERSION}.zip" ]; then
    echo "Could not fetch file from github"
    exit 1
fi

# extract it...
unzip  ${GEANT4_TMP_DIRECTORY}/v${GEANT4_VERSION}.zip -d ${GEANT4_TMP_DIRECTORY}
mv ${GEANT4_TMP_DIRECTORY}/geant4-${GEANT4_VERSION} ${GEANT4_SRC_DIRECTORY}

# configure it...
cd ${GEANT4_BUILD_DIRECTORY}
cmake -DCMAKE_INSTALL_PREFIX=${GEANT4_INSTALL_DIRECTORY} -DGEANT4_USE_QT=ON \
      -DGEANT4_USE_OPENGL_X11=ON -DGEANT4_INSTALL_DATA=ON -DGEANT4_USE_RAYTRACER_X11=ON \
      -DGEANT4_USE_GDML=ON  -DGEANT4_INSTALL_EXAMPLES=ON ${GEANT4_SRC_DIRECTORY}

# build and install it....
make -j 4
make install

# do some clean up...
rm -rf ${GEANT4_TMP_DIRECTORY}

echo "Finished installing geant4 version: ${GEANT4_VERSION}"