#!/usr/bin/env bash

echo "###################################"
echo "#                                 #"
echo "#  IMAGER software installation   #"
echo "#                                 #"
echo "###################################"
echo ""

# Script parameter
# empty -> get last available version
# or
# version number (ex: sep25) -> get the specified version


url="https://share.oasu.u-bordeaux.fr/imager"    # Archives url
Version=""

# Function: check_connection
# --------------------------
# Checks if a given URL is reachable using curl.
# Returns:
#   0 - if the connection is successful
#   1 - if the URL cannot be reached
check_connection() {
    local url=$1
    # Try to connect to the given URL with curl (HEAD request, silent mode, 5s timeout)
    if curl --head --silent --output /dev/null --connect-timeout 5 "$url"; then
        return 0
    else
        return 1
    fi
}

# Function: check_remote_file_exists
# ----------------------------------
# Checks if a specific file exists on a remote server using curl.
# Returns:
#   0 - if the file exists (server responds with success status)
#   1 - if the file does not exist (e.g., 404 Not Found)
check_remote_file_exists() {
    local url=$1
    local filename=$2
    # Try to check if the file exists by sending a HEAD request
    if curl --head --silent --output /dev/null --fail "$url/$filename"; then
        return 0
    else
        return 1
    fi
}


# MAIN CODE
# ---------

# 1. Retrieve the source code
if [[ "$#" = "0" ]] ; then
    Version="last"
    
    echo "Recovering last IMAGER sources from $url"

    # Check connexion
    check_connection $url
    rc=$?

    if [[ $rc = 1 ]]; then
        echo "Impossible to connect to $url. Exiting."
        exit 1
    fi

    # Check file existence
    check_remote_file_exists $url "imager-$Version.tgz"
    rcc=$?

    if [[ $rcc = 1 ]]; then
        echo "Impossible to get IMAGER version $Version. Exiting."
        exit 1
    fi

    # Get file
    curl -o imager-$Version.tgz $url/imager-$Version.tgz

    echo "Extracting imager-$Version.tgz to imager-src-* directory"
    tar -xf imager-last.tgz
    
    # Detect and store the real code version
    for dirname in */
    do
        if [[ "${dirname:0:10}" = "imager-src" ]] ; then
            if [[ "${dirname:16:1}" = "/" ]] ; then
                Version="${dirname:11:5}"
            fi
        fi
    done

else
    Version=$1
    
    # Check locally if an archive file is available for this version
    if [[ -f imager-$Version.tgz ]] || [[ -f imager-$Version.tar.gz ]] ; then

        # Get the first maching file
        filename=$(find . -name "imager-$Version.*" -type f | head -n 1 | cut -d"/" -f2)

        echo "Using the file $filename found locally"
        
        echo "Extracting $filename to imager-src-$Version directory"
        tar -xf "$filename"

    # Otherwise check remote url
    else
    
        echo "Recovering IMAGER version $Version from $url"

        # Check connexion
        check_connection $url
        rc=$?

        if [[ $rc = 1 ]]; then
            echo "Impossible to connect to $url. Exiting."
            exit 1
        fi

        # Check file existence
        check_remote_file_exists $url "imager-$Version.tgz"
        rcc=$?

        if [[ $rcc = 1 ]]; then
            echo "Impossible to get IMAGER version $Version. Exiting."
            exit 1
        else
            # Get file
            curl -o "imager-$Version.tgz" "$url/imager-$Version.tgz"
            echo "Extracting imager-$Version.tgz to imager-src-$Version directory"
            tar -xf "imager-$Version.tgz"
        fi

    fi

fi

echo "Using version $Version"
echo ""

unset answer
read -rp "-> Ready to continue (y/N) ? : " answer && [[ $answer == [yY] || $answer == [yY][eE][sS] ]] || exit 1


# 2. Compilation
if [[ -d "imager-src-$Version" ]]; then
    echo "Moving to imager-src-$Version"
elif [[ -d "imager-$Version" ]]; then
    mv "imager-$Version"  "imager-src-$Version"
else 
    echo "ERR: IMAGER version $Version not found. Exiting."
    exit 1
fi

# Patch until imager-env.sh has been updated (safe in all cases)
export my_exedir=$PWD/imager-exe-$Version         # Patch

# Ensure no conflict with other versions being compiled
unset gagsrcdir
unset gagexedir
unset gagadmdir


cd "imager-src-$Version" || exit 1

# Prepare the compilation scripts from Admin-Source
cd Admin-Source || exit 1
source substitute.compile.sh

cd .. || exit 1
# Execute the environment definition script
source admin/imager-env.sh -o openmp
export gagexedir=$my_exedir         # Patch

# Get the number of cores and leave one core free (but at least 1 job)
ncores=$(getconf _NPROCESSORS_ONLN)
jobs=$((ncores > 1 ? ncores - 1 : 1))

if (( jobs > 16 )); then
  jobs=16
fi
echo "Compilation will use $jobs threads in parallel"
#
# Get confirmation
echo "Ready to compile IMAGER in $gagsrcdir."
read -rp "-> Continue (y/N)? : " answer && [[ $answer == [yY] || $answer == [yY][eE][sS] ]] || exit 1

make -j"$jobs"

echo "Ready to install IMAGER on $gagexedir."
read -rp "-> Continue (y/N)? : " answer && [[ $answer == [yY] || $answer == [yY][eE][sS] ]] || exit 1

make install

cd .. || exit 1
