#!/bin/sh
#
# Update the Sherpa configuration file (setup.cfg) and rc file 
# (sherpa-standalone.rc -> sherpa.rc) to use the
# CIAO conda installation.
#

# Check we have the CIAO installation available.
#
if [ "x$ASCDS_INSTALL" = "x" ]; then
    echo "ERROR: The ASCDS_INSTALL environment variable is not set";
    exit 1;
fi

if [ ! -d $ASCDS_INSTALL ]; then
    echo "ERROR: ASCDS_INSTALL does not point to a directory";
    exit 1;
fi

# Extract the XSPEC version from the conda packaging metadata;
# hopefully the formatting and structure remain consistent.
#
xspec_version="12.14.0"

# Are we in the right directory
#
cfg=setup.cfg
if [ ! -f $cfg ]; then
    echo "ERROR: Unable to find $cfg";
    exit 1;
fi

# Check the file has not been changed (this could be relaxed but
# try this approach first).
#
git diff --exit-code $cfg > /dev/null
if [ $? -ne 0 ]; then
    echo "ERROR: $cfg has already been changed."
    exit 1;
fi

# Apply the changes line-by-line
#
echo "Updating $cfg"

sed -i="" "s|#install_dir=build|install_dir=${ASCDS_INSTALL}|" $cfg

sed -i="" "s|#disable_group=True|disable_group=True|" $cfg
sed -i="" "s|#disable_stk=True|disable_stk=True|" $cfg

sed -i="" "s|#region=local|region=local|" $cfg
sed -i="" "s|#region*include_dirs=build/include|region_include_dirs=${ASCDS_INSTALL}/include|" $cfg
sed -i="" "s|#region_lib_dirs=build/lib|region_lib_dirs=${ASCDS_INSTALL}/lib|" $cfg
sed -i="" "s|#region_libraries=region|region_libraries=region ascdm|" $cfg
sed -i="" "s|#region_use_cxc_parser=False|region_use_cxc_parser=True|" $cfg

sed -i="" "s|#wcs=local|wcs=local|" $cfg
# Historically the setup file has used the wrong form here
# so support both 'include-dirs' and 'include_dirs'.
sed -i="" "s|#wcs*include.dirs=build/include|wcs_include_dirs=${ASCDS_INSTALL}/include|" $cfg
sed -i="" "s|#wcs_lib_dirs=build/lib|wcs_lib_dirs=${ASCDS_INSTALL}/lib|" $cfg
sed -i="" "s|#wcs_libraries=wcs|wcs_libraries=wcs|" $cfg

sed -i="" "s|#fftw=local|fftw=local|" $cfg
sed -i="" "s|#fftw_include_dirs=build/include|fftw_include_dirs=${ASCDS_INSTALL}/include|" $cfg
sed -i="" "s|#fftw_lib_dirs=build/lib|fftw_lib_dirs=${ASCDS_INSTALL}/lib|" $cfg
sed -i="" "s|#fftw_libraries=fftw3|fftw_libraries=fftw3|" $cfg

sed -i="" "s|#with_xspec=True|with_xspec=True|" $cfg
sed -i="" "s|#xspec_include_dirs = None|xspec_include_dirs=${ASCDS_INSTALL}/include|" $cfg
sed -i="" "s|#xspec_lib_dirs = None|xspec_lib_dirs=${ASCDS_INSTALL}/lib|" $cfg
sed -i="" "s|#xspec_version = .*|xspec_version = ${xspec_version}|" $cfg

echo "Updating rc file name in sherpa/__init__.py"
sed -i="" "s|sherpa-standalone.rc|sherpa.rc|g" sherpa/__init__.py

# Depending on the version of sed, there might be a temporary file. Remove it if it exists.
rm -f setup.cfg= sherpa/__init__.py=

echo "Creating extern/built to skip the extern directory"
touch extern/built
