#!/usr/bin/env bash
#
# Copyright 2013-2024 Axel Huebl, Rene Widera, Pawel Ordyna
#
# This file is part of PIConGPU.
#
# PIConGPU 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.
#
# PIConGPU 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.
#
# You should have received a copy of the GNU General Public License
# along with PIConGPU.
# If not, see <http://www.gnu.org/licenses/>.
#

this_dir=$(cd $(dirname $0) && pwd)

# PIConGPU prefix path
picongpu_prefix=$(cd $this_dir/.. && pwd)

function absolute_path()
{
    cd $1
    pwd
}

help()
{
    echo "Configure PIConGPU with CMake"
    echo ""
    echo "Generates a call to CMake and provides short-hand access to selected"
    echo "PIConGPU CMake options."
    echo "Advanced users can always run 'ccmake .' after this call for further"
    echo "compilation options."
    echo ""
    echo "usage: pic-configure [OPTIONS] <inputDirectory>"
    echo ""
    echo "-i | --install        - path were picongpu shall be installed"
    echo "                       (default is <inputDirectory>)"
    echo "-b | --backend        - set compute backend and optionally the architecture"
    echo "                        syntax: backend[:architecture]"
    echo "                        supported backends: cuda, hip, omp2b, serial, tbb, threads"
    echo "                        (e.g.: \"cuda:35;37;52;60\" or \"omp2b:native\" or \"omp2b\")"
    echo "                        default: \"cuda\" if not set via environment variable PIC_BACKEND"
    echo "                        note: architecture names are compiler dependent"
    echo "-c | --cmake          - overwrite options for cmake"
    echo "                        (e.g.: \"-DPIC_VERBOSE=21 -DCMAKE_BUILD_TYPE=Debug\")"
    echo "-t <presetNumber>     - configure this preset from cmakeFlags"
    echo "-f | --force          - clear the cmake file cache and scan for new param files"
    echo "-G <cmakeBuildSystem> - select the build system used by CMake, e.g. Ninja, ..."
    echo "-h | --help           - show this help message"
}

get_backend_flags()
{
    # Everything before the first : is the backend, the rest is the architecture definition which could contain : too.
    cfg="$(echo -n $1 | sed 's/:/=/')"
    backend_cfg=(${cfg//=/ })
    num_options="${#backend_cfg[@]}"
    if [ $num_options -gt 2 ] ; then
        echo "-b|--backend must be contain 'backend:arch' or 'backend'" >&2
        exit 1
    fi
    if [ "${backend_cfg[0]}" == "cuda" ] ; then
        # -Dalpaka_CUDA_EXPT_EXTENDED_LAMBDA=ON is a workaround for https://github.com/alpaka-group/alpaka/pull/1401
        # what is not part of alpaka 0.7.0
        result+=" -Dalpaka_ACC_GPU_CUDA_ENABLE=ON -Dalpaka_ACC_GPU_CUDA_ONLY_MODE=ON -Dalpaka_CUDA_EXPT_EXTENDED_LAMBDA=ON"
        if [ $num_options -eq 2 ] ; then
            result+=" -DCMAKE_CUDA_ARCHITECTURES=${backend_cfg[1]}"
        else
            result+=" -DCMAKE_CUDA_ARCHITECTURES=52"
        fi
    elif [ "${backend_cfg[0]}" == "omp2b" ] ; then
        result+=" -Dalpaka_ACC_CPU_B_OMP2_T_SEQ_ENABLE=ON -DPMACC_ASYNC_QUEUES=OFF"
        if [ $num_options -eq 2 ] ; then
            result+=" -DPMACC_CPU_ARCH=${backend_cfg[1]}"
        fi
    elif [ "${backend_cfg[0]}" == "serial" ] ; then
        result+=" -Dalpaka_ACC_CPU_B_SEQ_T_SEQ_ENABLE=ON -DPMACC_ASYNC_QUEUES=OFF"
        if [ $num_options -eq 2 ] ; then
            result+=" -DPMACC_CPU_ARCH=${backend_cfg[1]}"
        fi
    elif [ "${backend_cfg[0]}" == "tbb" ] ; then
        result+=" -Dalpaka_ACC_CPU_B_TBB_T_SEQ_ENABLE=ON -DPMACC_ASYNC_QUEUES=OFF"
        if [ $num_options -eq 2 ] ; then
            result+=" -DPMACC_CPU_ARCH=${backend_cfg[1]}"
        fi
    elif [ "${backend_cfg[0]}" == "threads" ] ; then
        result+=" -Dalpaka_ACC_CPU_B_SEQ_T_THREADS_ENABLE=ON -DPMACC_ASYNC_QUEUES=OFF"
        if [ $num_options -eq 2 ] ; then
            result+=" -DPMACC_CPU_ARCH=${backend_cfg[1]}"
        fi
    elif [ "${backend_cfg[0]}" == "hip" ] ; then
        result+=" -Dalpaka_ACC_GPU_HIP_ENABLE=ON -Dalpaka_ACC_GPU_HIP_ONLY_MODE=ON"
        if [ $num_options -eq 2 ] ; then
            result+=" -DCMAKE_HIP_ARCHITECTURES=${backend_cfg[1]}"
        fi
    else
        echo "unsupported backend given '$1'" >&2
        exit 1
    fi

    echo "$result"
    exit 0
}

# options may be followed by one colon to indicate they have a required argument
OPTS=`getopt -o G:i:b:c:p:t:hf -l install:,backend:,cmake:,params:,help,force -- "$@"`
if [ $? != 0 ] ; then
    # something went wrong, getopt will put out an error message for us
    exit 1
fi

# configure a specific preset in the cmakeFlags file
# note: can be overwritten with a command line flag
cmakeFlagsNr=-1

# set a default backend (and architecture) if supplied via environment var
# note: can be overwritten with a command line flag
pic_backend=${PIC_BACKEND:-"cuda"}
if [ -n "$pic_backend" ]
then
    alpaka_backend=$(get_backend_flags $pic_backend)
fi

eval set -- "$OPTS"

while true ; do
    case "$1" in
        -b|--backend)
            alpaka_backend=$(get_backend_flags $2)
            if [ $? -ne 0 ] ; then
                exit 1
            fi
            shift
            ;;
        -i|--install)
            install_path="-DCMAKE_INSTALL_PREFIX=$2"
            shift
            ;;
        -h|--help)
            echo -e "$(help)"
            exit 0
            ;;
        -f|--force)
            force="true"
            ;;
        -c|--cmake)
            cmake_options="$2"
            shift
            ;;
        -G)
           buildSystem="-G $2"
           shift
            ;;
        -t)
            cmakeFlagsNr="$2"
            shift
            ;;
        --) shift; break;;
    esac
    shift
done

extension_param="$(absolute_path $*)"

if [ ! -d "$extension_param" ] ; then
    echo "Path \"$extension_param\" does not exist." >&2
    exit 1
fi
# check for cmakeFlags file (interprete with sh)
if [ -f "$extension_param/cmakeFlags" ] ; then
    if [ $cmakeFlagsNr -eq -1 ] ; then
        # if the user has not given this value use zero as default.
        cmakeFlagsNr=0
    fi
    num_cmake_flags=$($extension_param/cmakeFlags -l)
    if [ $? -ne 0 ] ; then
        echo "ERROR: Executing '$extension_param/cmakeFlags -l' failed!" >&2
        echo "       Is the file executable? (chmod u+x cmakeFlags)" >&2
        exit 2
    fi
    if [ $cmakeFlagsNr -ge $num_cmake_flags ] ; then
        echo "ERROR: Executing '$extension_param/cmakeFlags $cmakeFlagsNr' failed!" >&2
        echo "       Requested preset '$cmakeFlagsNr' does not exist, '$num_cmake_flags' presets found." >&2
        exit 2
    fi
    cmake_flags=$($extension_param/cmakeFlags $cmakeFlagsNr)
    if [ $? -ne 0 ] ; then
        echo "ERROR: Executing '$extension_param/cmakeFlags' failed!" >&2
        exit 2
    fi
    # save the cmakeFlags setup number for future reference
    if [ -f "$extension_param/cmakeFlagsSetup" ] ; then
      rm $extension_param/cmakeFlagsSetup
    fi
    touch $extension_param/cmakeFlagsSetup
    echo "Last configured cmakeFlags setup was the setup No.: $cmakeFlagsNr" > $extension_param/cmakeFlagsSetup
    echo $cmake_flags >> $extension_param/cmakeFlagsSetup
elif [ $cmakeFlagsNr -ne -1 ] ; then
    echo "ERROR: '$extension_param/cmakeFlags' not exists!" >&2
    echo "       Therefore option -t can not be used." >&2
    exit 2
fi

# legacy check: we removed simulation_defines/ after PIConGPU 0.3.X
if [ -d "$extension_param/include/picongpu/simulation_defines" ] ; then
    echo "ERROR: simulation_defines/ directory found!" >&2
    echo "       Please update your input directory to the new structure!" >&2
    exit 3
fi

# set default install path if no path is set by parameter
if [ -z "$install_path" ] ; then
    install_path="-DCMAKE_INSTALL_PREFIX=$extension_param"
fi
cmake_extension_param="-DPIC_EXTENSION_PATH=$extension_param"

# warn on missing backend selection
if [ -z "$alpaka_backend" ] ; then
    echo "Warning: no compute backend set! " >&2
    echo "(Use -b|--backend or export PIC_BACKEND)" >&2
fi

if [ "$force" == "true" ] && [ -f "CMakeCache.txt" ] ; then
    clean_cmd="cmake ${buildSystem} --build . --target clean"
    echo -e "\033[32mforce clean the build directory:\033[0m $clean_cmd"
    eval $clean_cmd
fi
own_command="cmake ${buildSystem} $cmake_flags $install_path $cmake_extension_param $cmake_options $alpaka_backend $picongpu_prefix/include/picongpu"
echo -e "\033[32mcmake command:\033[0m $own_command"
eval $own_command
