#! /bin/sh
#
# Necessary preparations/configurations for the reproduction pipeline.
#
# Original author:
#     Mohammad Akhlaghi <mohammad@akhlaghi.org>
# Contributing author(s):
#     Your name <your@email.address>
# Copyright (C) 2018, Your Name.
#
# This script is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# A copy of the GNU General Public License is available at
# <http://www.gnu.org/licenses/>.





# Script settings
# ---------------
# Stop the script if there are any errors.
set -e





# Important internal locations
# ----------------------------
#
# These are defined to help make this script more readable.
topdir=$(pwd)
installedlink=.local
lbdir=reproduce/build
cdir=reproduce/config
optionaldir="/optional/path"

pdir=$cdir/pipeline
pconf=$pdir/LOCAL.mk
ptconf=$pdir/LOCAL_tmp.mk
poconf=$pdir/LOCAL_old.mk
# --------- Delete for no Gnuastro ---------
glconf=$cdir/gnuastro/gnuastro-local.conf
# ------------------------------------------





# Delete final target of configuration
# ------------------------------------
#
# Without the top-level `Makefile' the user can't run `make' in this
# directory. But we only want to make it available when we know everything
# else is set up. So we'll delete it at the start of this configuration and
# reset the link in the absolute end.
rm -f Makefile





# Notice for top of generated files
# ---------------------------------
#
# In case someone opens the files output from the configuration scripts in
# a text editor and wants to edit them, it is important to let them know
# that their changes are not going to be permenant.
function create_file_with_notice() {
    if echo "# IMPORTANT: file can be RE-WRITTEN after './configure'"  > $1
    then
        echo "#"                                                      >> $1
        echo "# This file was created during the reproduction"        >> $1
        echo "# pipeline's configuration ('./configure'). Therefore," >> $1
        echo "# it is not under version control and any manual "      >> $1
        echo "# changes to it will be over-written if the pipeline "  >> $1
        echo "# is re-configured."                                    >> $1
        echo "#"                                                      >> $1
    else
        echo; echo "Can't write to $1"; echo;
        exit 1
    fi
}





# Get absolute address
# --------------------
#
# Since the build directory will go into a symbolic link, we want it to be
# an absolute address. With this function we can make sure of that.
function absolute_dir() {
    echo "$(cd "$(dirname "$1")" && pwd )/$(basename "$1")"
}





# Inform the user
# ---------------
#
# Print some basic information so the user gets a feeling of what is going
# on and is prepared on what will happen next.
cat <<EOF

-----------------------------------------
Reproduction pipeline local configuration
-----------------------------------------

Local configuration includes things like top-level directories, or
processing steps.

It is STRONGLY recommended to read the comments, and set the best values
for your system (where necessary).

EOF





# What to do with possibly existing configuration file
# ----------------------------------------------------
#
# `LOCAL.mk' is the top-most local configuration for the pipeline. If it
# already exists when this script is run, we'll make a copy of it as backup
# (for example the user might have ran `./configure' by mistake).
printnotice=yes
rewritepconfig=yes
rewritegconfig=yes
if [ -f $pconf ] || [ -f $glconf ]; then

    # If it already exits, see what the user wants to do.
    echo "Atleast one local configuration file already exists."
    echo
    while [ "$userread" != "y" -a "$userread" != "n" ]
    do
        read -p"Re-write existing configuration file(s) (y/n)? " userread
    done

    # Set `rewriteconfig'.
    if [ $userread = "n" ]; then
        printnotice=no
        if [ -f $pconf  ]; then rewritepconfig=no; fi
        if [ -f $glconf ]; then rewritegconfig=no; fi
    fi
    echo
fi





# Identify the downloader tool
# ----------------------------
#
# After this `./configure' script finishes, we will have both Wget and cURL
# for downloading any necessary dataset during the processing. However, to
# complete the configuration, we may also need to download the source code
# of some necessary software packages (including the downloaders). So we
# need to check the host's available tool for downloading at this step.
if [ $rewritepconfig = yes ]; then
    if type wget > /dev/null 2>/dev/null; then
        name=$(which wget)

        # By default Wget keeps the remote file's timestamp, so we'll have
        # to disable it manually.
        downloader="$name --no-use-server-timestamps -O";
    elif type curl > /dev/null 2>/dev/null; then
        name=$(which curl)

        # - cURL doesn't keep the remote file's timestamp by default.
        # - With the `-L' option, we tell cURL to follow redirects.
        downloader="$name -L -o"
    else
        cat <<EOF

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!         Warning        !!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Couldn't find GNU Wget. It is used for downloading necessary programs and
data if they aren't already present in the specified directories. Therefore
the pipeline will crash if the necessary files are not already present on
the system.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

EOF
        downloader="no-downloader-found"
    fi;
fi





# Build directory
# ---------------
if [ $rewritepconfig = yes ]; then
    cat <<EOF

===============
Build directory
===============

The "source" (this directory) and "build" directories are treated
separately. This greatly helps in managing the many intermediate files that
are created during the build. The intermediate build files don't need to be
archived or backed up: you can always re-build them with this reproduction
pipeline. The build directory also needs a relatively large amount of free
space (atleast serveral Giga-bytes).

'$lbdir' (a symbolic link to the build directory) will also be created
during this configuration. It can help encourage you to set the actual
build directory in a very different address from this one (one that can be
deleted and has large volume), while having easy access to it from here.

EOF
    bdir=""
    junkname=pure-junk-974adfkj38
    while [ x$bdir == x ]
    do
        # Ask the user.
        read -p"Please enter the top build directory: " inbdir

        # If it exists, see if we can write in it. If not, try making it.
        if [ -d $inbdir ]; then
            if mkdir $inbdir/$junkname 2> /dev/null; then
                bdir=$(absolute_dir $inbdir)
                echo " -- Build directory: '$bdir'"
                rm -rf $inbdir/$junkname
            else
                echo " -- Can't write in '$inbdir'"
            fi
        else
            if mkdir $inbdir 2> /dev/null; then
                bdir=$(absolute_dir $inbdir)
                echo " -- Build directory set to (the newly created): '$bdir'"
            else
                echo " -- Can't create '$inbdir'"
            fi
        fi
    done
fi





# Input directory
# ---------------
indir=$optionaldir
wfpc2name=$(awk '!/^#/ && $1=="WFPC2IMAGE" {print $3}' $pdir/INPUTS.mk)
wfpc2md5=$(awk  '!/^#/ && $1=="WFPC2MD5"   {print $3}' $pdir/INPUTS.mk)
wfpc2size=$(awk '!/^#/ && $1=="WFPC2SIZE"  {print $3}' $pdir/INPUTS.mk)
wfpc2url=$(awk  '!/^#/ && $1=="WFPC2URL"   {print $3}' $pdir/INPUTS.mk)
if [ $rewritepconfig = yes ]; then
    cat <<EOF

----------------------------------
(OPTIONAL) Input dataset directory
----------------------------------

This pipeline needs the dataset(s) listed below. If you already have them,
please specify the directory hosting them on this system. If you don't,
they will be downloaded automatically. Each file is shown with its total
volume and its 128-bit MD5 checksum in parenthesis.

  $wfpc2name ($wfpc2size, $wfpc2md5):
    A 100x100 Hubble Space Telescope WFPC II image used in the FITS
    standard webpage as a demonstration of this file format.
    URL: $wfpc2url/$wfpc2name

NOTE: This directory, or the datasets above, are optional. If it doesn't
exist, the files will be downloaded in the build directory and used.

TIP: If you have these files in multiple directories on your system and
don't want to download them or make duplicates, you can create symbolic
links to them and put those symbolic links in the given top-level
directory.

EOF
    read -p"(OPTIONAL) Input datasets directory ($indir): " inindir
    if [ x$inindir != x ]; then
        indir=$inindir
        echo " -- Using '$indir'"
    fi
fi





# Dependency tarball directory
# ----------------------------
if [ $rewritepconfig = yes ]; then
    ddir=$optionaldir
    cat <<EOF

---------------------------------------
(OPTIONAL) Dependency tarball directory
---------------------------------------

To ensure an identical build environment, the pipeline will use its own
build of the programs it needs. Therefore the tarball of the relevant
programs are necessary for this pipeline. If a tarball isn't present in the
specified directory, *IT WILL BE DOWNLOADED* by the pipeline.

Therefore, if you don't specify any directory here, or it doesn't contain
the tarball of a dependency, it is necessary to have an internet
connection. The pipeline will download the tarballs it needs automatically.

EOF
    read -p"(OPTIONAL) Directory of dependency tarballs ($ddir): " tmpddir
    if [ x"$tmpddir" != x ]; then
        ddir=$tmpddir
        echo " -- Using '$ddir'"
    fi
fi





# Memory mapping minimum size
# ---------------------------
if [ $rewritegconfig = yes ]; then
    defaultminmapsize=10000000000
    minmapsize=$defaultminmapsize
    cat <<EOF

---------------------------
Minimum memory mapping size
---------------------------

Some programs (for example Gnuastro) can deal with cases where the local
system doesn't have enough memory (RAM) to keep large files. For example,
they will create memory-mapped (mmap) files on the HDD or SSD and
read/write to/from them instead of RAM. This will ofcourse, slow down the
processing, but atleast the program won't crash.

Since the memory requirements of different systems are different and it has
no effect on the software's final result, the minimum size of an allocated
array to warrant a mapping to HDD/SSD instead of RAM must also be defined
here. This value will be used in the programs that support this feature.

EOF

    read -p"Minimum memory mapping size in bytes (default: $minmapsize): " \
         tmpminmapsize
    if [ x"$tmpminmapsize" != x ]; then
        minmapsize=$tmpminmapsize
        echo " -- Using '$minmapsize'"
    fi
fi





# Write the parameters into the local configuration file.
if [ $rewritepconfig = yes ]; then
    create_file_with_notice $pconf
    sed -e's|@bdir[@]|'"$bdir"'|'              \
        -e's|@indir[@]|'"$indir"'|'            \
        -e's|@ddir[@]|'"$ddir"'|'              \
        -e's|@downloader[@]|'"$downloader"'|'  \
        $pconf.in >> $pconf
else
    # Read the values from existing configuration file.
    inbdir=$(awk     '$1=="BDIR"             {print $3}' $pconf)
    downloader=$(awk '$1=="DOWNLOADER"       {print $3}' $pconf)

    # Make sure all necessary variables have a value
    err=0
    verr=0
    novalue=""
    if [ x"$inbdir"     = x ]; then novalue="BDIR, ";              fi
    if [ x"$downloader" = x ]; then novalue="$novalue"DOWNLOADER;  fi
    if [ x"$novalue"   != x ]; then verr=1; err=1;                 fi

    # Make sure `bdir' is an absolute path and it exists.
    berr=0
    ierr=0
    bdir=$(absolute_dir $inbdir)

    if ! [ -d $bdir  ]; then if ! mkdir $bdir; then berr=1; err=1; fi; fi
    if [ $err = 1 ]; then
        cat <<EOF

#################################################################
########  ERORR reading existing configuration file  ############
#################################################################
EOF
        if [ $verr = 1 ]; then
            cat <<EOF

These variables have no value: $novalue.
EOF
        fi
        if [ $berr = 1 ]; then
           cat <<EOF

Couldn't create the build directory '$bdir' (value to 'BDIR') in
'$pconf'.
EOF
        fi

        cat <<EOF

Please run the configure script again (accepting to re-write existing
configuration file) so all the values can be filled and checked.
#################################################################
EOF
    fi
fi





# --------- Delete for no Gnuastro ---------
# Get the version of Gnuastro that must be used.
depverfile=reproduce/config/pipeline/dependency-versions.mk
gversion=$(awk '$1=="gnuastro-version" {print $NF}' $depverfile)

# Gnuastro's local configuration settings
if [ $rewritegconfig = yes ]; then
    create_file_with_notice $glconf
    echo "# Minimum number of bytes to use HDD/SSD instead of RAM." >> $glconf
    echo " minmapsize $minmapsize"                                  >> $glconf
    echo                                                            >> $glconf
    echo "# Version of Gnuastro that must be used."                 >> $glconf
    echo " onlyversion $gversion"                                   >> $glconf
else
    ingversion=$(awk '$1=="onlyversion" {print $NF}' $glconf)
    if [ x$ingversion != x$gversion ]; then
        echo "______________________________________________________"
        echo "!!!!!!!!!!!!!!!!!!CONFIGURATION ERROR!!!!!!!!!!!!!!!!!"
        echo
        echo "Gnuastro's version in '$glconf' ($ingversion) doesn't match the tarball version that this pipeline was designed to use in '$depverfile' ($gversion). Please re-run after removing the former file:"
        echo
        echo "   $ rm $glconf"
        echo "   $ ./configure"
        echo
        echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        echo
        exit 1
    fi
fi
# ------------------------------------------





# Setup the top-level directories
# -------------------------------
rm -f $lbdir
ln -s $bdir $lbdir

depdir=$bdir/dependencies
if ! [ -d $depdir ];  then mkdir $depdir; fi

tardir=$depdir/tarballs
if ! [ -d $tardir ];  then mkdir $tardir; fi

instdir=$depdir/installed
if ! [ -d $instdir ]; then mkdir $instdir; fi

rm -f $installedlink
ln -s $instdir $installedlink

# --------- Delete for no Gnuastro ---------
rm -f .gnuastro
ln -s $(pwd)/reproduce/config/gnuastro .gnuastro
# ------------------------------------------





# See if the C compiler can build static libraries
# ------------------------------------------------

# We are manually only working with shared libraries: because some
# high-level programs like Wget and cURL need dynamic linking and if we
# build the libraries statically, our own builds will be ignored and these
# programs will go and find their necessary libraries on the host system.
#
# Another good advantage of shared libraries is that we can actually use
# the shared library tool of the system (`ldd' with GNU C Library) and see
# exactly where each linked library comes from. But in static building,
# unless you follow the build closely, its not easy to see if the source of
# the library came from the system or our build.
static_build=no

#oprog=$depdir/static-test
#cprog=$depdir/static-test.c
#echo "#include <stdio.h>"          > $cprog
#echo "int main(void) {return 0;}" >> $cprog
#if [ x$CC = x ]; then CC=gcc; fi;
#if $CC $cprog -o$oprog -static &> /dev/null; then
#    export static_build="yes"
#else
#    export static_build="no"
#fi
#rm -f $oprog $cprog
#if [ $printnotice = yes ] && [ $static_build = "no" ]; then
#    cat <<EOF
#_________________________________________________________________________
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!      WARNING      !!!!!!!!!!!!!!!!!!!!!!!!!!
#
#Your system's C compiler ('$CC') doesn't support building static
#libraries. Therefore the dependencies will be built dynamically. This means
#that they will depend more strongly on changes/updates in the host
#system. For high-level applications (like most research projects in natural
#sciences), this shouldn't be a significant problem.
#
#But generally, for reproducibility, its better to build static libraries
#and programs. For more on their difference (and generally an introduction
#on linking), please see the link below:
#
#https://www.gnu.org/software/gnuastro/manual/html_node/Linking.html
#
#If you have other compilers on your system, you can select a different
#compiler by setting the 'CC' environment variable before running
#'./configure'.
#
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#
#EOF
#    sleep 5
#fi





# See if the linker accepts -Wl,-rpath-link
# -----------------------------------------
#
# `-rpath-link' is used to write the information of the linked shared
# library into the shared object (library or program). But some versions of
# LLVM's linker don't accept it an can cause problems.
oprog=$depdir/rpath-test
cprog=$depdir/rpath-test.c
echo "#include <stdio.h>"          > $cprog
echo "int main(void) {return 0;}" >> $cprog
if [ x$CC = x ]; then CC=gcc; fi;
if $CC $cprog -o$oprog -Wl,-rpath-link &> /dev/null; then
    export rpath_command="-Wl,-rpath-link=$instdir/lib"
else
    export rpath_command=""
fi
rm -f $oprog $cprog





# See if we need the dynamic-linker (-ldl)
# ----------------------------------------
#
# Some programs (like Wget) need dynamic loading (using `libdl'). On
# GNU/Linux systems, we'll need the `-ldl' flag to link such programs.  But
# Mac OS doesn't need any explicit calling. So we'll check here to use in
# the building of programs.
oprog=$depdir/ldl-test
cprog=$depdir/ldl-test.c
cat > $cprog <<EOF
#include <stdio.h>
#include <dlfcn.h>
int
main(void) {
    void *handle=dlopen ("/lib/CEDD_LIB.so.6", RTLD_LAZY);
    return 0;
}
EOF
if gcc $cprog -o$oprog &> /dev/null; then needs_ldl=no; else needs_ldl=yes; fi
rm -f $oprog $cprog





# inform the user that the build process is starting
# -------------------------------------------------
if [ $printnotice = yes ]; then
    tsec=10
    cat <<EOF

-------------------------
Building dependencies ...
-------------------------

Necessary dependency programs and libraries will be built in $tsec sec.

NOTE: the built software will NOT BE INSTALLED on your system (no root
access is required). They are only for local usage by this reproduction
pipeline. They will be installed in:

  $bdir/dependencies/installed

EOF
    sleep $tsec
fi





# If we are on a Mac OS system
# ----------------------------
#
# For the time being, we'll use the existance of `otool' to see if we are
# on a Mac OS system or not. Some tools (for example OpenSSL) need to know
# this.
if type otool > /dev/null 2>/dev/null; then
    on_mac_os=yes
else
    on_mac_os=no
fi





# Build Basic dependencies
# ------------------------
#
# Since the system might not have GNU Coreutils at this stage, we'll just
# default to 4 threads if the actual number isn't found. This is because
# some versions of Make complain about not having enough 'pipe' (memory) on
# some systems. After some searching, I found out its because of too many
# threads.
if which nproc > /dev/null 2>/dev/null; then numthreads=$(nproc --all);
else                                         numthreads=1;
fi
make -f reproduce/src/make/dependencies-basic.mk \
     rpath_command=$rpath_command                \
     static_build=$static_build                  \
     needs_ldl=$needs_ldl                        \
     on_mac_os=$on_mac_os                        \
     -j$numthreads





# Rest of dependencies
# --------------------
#
# We will be making all the dependencies before running the top-level
# Makefile. To make the job easier, we'll do it in a Makefile, not a
# script. Bash and Make were the tools we need to run Makefiles, so we had
# to build them in this script. But after this, we can rely on Makefiles.
numthreads=$($instdir/bin/nproc)
./.local/bin/make -f reproduce/src/make/dependencies.mk    \
                  rpath_command=$rpath_command             \
                  static_build=$static_build               \
                  on_mac_os=$on_mac_os                     \
                  -j$numthreads





# Make sure TeX Live installed successfully
# -----------------------------------------
#
# TeX Live is managed over the internet, so if there isn't any, or it
# suddenly gets cut, it can't be built. However, when TeX Live isn't
# installed, the pipeline and can do all its processing independent of
# it. It will just stop at the stage when all the processing is complete
# and it is only necessary to build the PDF.  So we don't want to stop the
# pipeline if its not present.
texlive_result=$(cat $instdir/bin/texlive-ready-tlmgr)
if [ x"$texlive_result" = x"NOT!" ]; then
    cat <<EOF

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!         Warning        !!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

TeX Live couldn't be installed during the configuration (probably because
there were downloading problems). TeX Live is only necessary in making the
final PDF (which is only done after all the analysis has been complete). It
is not used at all during the analysis.

Therefore, if you don't need the final PDF, and just want to do the
analysis, you can safely ignore this warning and continue.

If you later have internet access and would like to add TeX live to your
pipeline, please delete the respective files, then re-run configure as
shown below. Within configure, answer 'n' (for "no") when asked to re-write
the configuration files.

    rm .local/bin/texlive-ready-tlmgr
    ./configure

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

EOF
fi





# Final step: the Makefile
# --------------------------
#
# To see why this is the last step of the configuration, see above (when we
# delete the top-level Makefile at the start of this script).
ln -s $(pwd)/reproduce/src/make/top.mk Makefile





# Final notice
# ------------
#
# The configuration is now complete, we can inform the user on the next
# step(s) to take.
cat <<EOF

----------------
The reproduction pipeline and its environment are configured with no errors.

Please run the following command to start.
(Replace '8' with the number of CPU threads)

    .local/bin/make -j8

To change the configuration later, please re-run './configure',
DO NOT manually edit the relevant files.

EOF