# Copyright 2016 Intel Corporation All Rights Reserved.
#
# The source code contained or described herein and all documents
# related to the source code ("Material") are owned by Intel
# Corporation or its suppliers or licensors. Title to the Material
# remains with Intel Corporation or its suppliers and licensors. The
# Material may contain trade secrets and proprietary and confidential
# information of Intel Corporation and its suppliers and licensors,
# and is protected by worldwide copyright and trade secret laws and
# treaty provisions. No part of the Material may be used, copied,
# reproduced, modified, published, uploaded, posted, transmitted,
# distributed, or disclosed in any way without Intel's prior express
# written permission.
#
# No license under any patent, copyright, trade secret or other
# intellectual property right is granted to or conferred upon you by
# disclosure or delivery of the Materials, either expressly, by
# implication, inducement, estoppel or otherwise. Any license under
# such intellectual property rights must be express and approved by
# Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or
# alter this notice or any other notice embedded in Materials by Intel
# or Intel's suppliers or licensors in any way.

# Setup the Intel(R) C++ Compiler shell environment for the latest
# installed version.  The exit status is 0 if successful, 1 otherwise.
# First tries /opt/intel/composerxe/bin/compilervars.sh, and if that
# does not exist, tries /opt/intel/cce/x.y.z/bin/iccvars.sh where
# x.y.z is the largest (i.e., latest) value if multiple versions are
# installed.
function compilervars() {
    local base="/opt/intel/composerxe"

    _arch_token

    if [ -e "${base}/bin/compilervars.sh" ] ; then
        source ${base}/bin/compilervars.sh ${_arch_token}
        return 0
    fi

    # redefine $base
    base="/opt/intel/cce"
    local versions=`\find ${base} -maxdepth 1 -regex "${base}/[0-9\.]*" -print 2> /dev/null | awk -F/ '{print $5}'`
    if [[ "$versions" == "" ]] ; then
        _stderr "no version of Intel(R) C++ Compiler found"
        return 1
    fi

    local maxver="0.0.0"
    for version in ${versions}
    do
        _vercmp $version $maxver
        if [ $? == 1 ] ; then
            maxver=$version
        fi
    done

    local iccvars="${base}/${maxver}/bin/iccvars.sh"
    if [ -e ${iccvars} ] ; then
        source ${iccvars}
        return 0
    fi

    return 1
}

# Defines a variable named $memory_size that contains the memory size
# in megabytes (default).  If not successful, $memory_size = 0 and the
# exit status is 1.
function memory_size() {
    local conversion=1024 # default to MB
    memory_size=0

    # silently ignore unrecognized options
    case "$1" in
        "KB" | "kb")
            conversion=1
            ;;
        "MB" | "mb")
            conversion=1024
            ;;
    esac

    # /proc/meminfo units are KB
    local mem=`\grep "MemTotal:" /proc/meminfo | awk '{printf "%d", $2}'`
    if [[ $? == 0 && -n ${mem} ]] ; then
        memory_size=$((${mem} / ${conversion})) # convert KB to ...
        return 0
    fi

    _stderr "could not determine the memory size"
    return 1
}

# Defines a variable named $memory_size_cluster_min that contains the
# minimum memory size across a set of nodes.  If not successful,
# $memory_size_cluster_min = 0 and the exit status is 1.
function memory_size_cluster_min() {
    local nodefile=$1
    local prefix=$2
    local units=$3
    memory_size_cluster_min=0

    _arch_token

    local pdsh="${prefix}/../../../bin/${_arch_token}/pdsh"
    local self="${prefix}/../../functions"

    if [ ! -f "$pdsh" ] ; then
        _stderr "could not find pdsh"
        return 1
    fi

    if [ ! -f "$self" ] ; then
        _stderr "could not find functions"
        return 1
    fi

    local mem=`$pdsh -N -w ^$nodefile ". $self && memory_size $units && echo \\\$memory_size" | sort -un | head -1`
    if [[ $? == 0 && -n ${mem} && ${mem} =~ ^[0-9]+$ ]] ; then
        memory_size_cluster_min=$mem
        return 0
    fi

    _stderr "could not determine the minimum cluster memory size"
    return 1
}

# Defines a variable named $min_mic_count that contains the min number
# of coprocessors installed on any one node in the node file. If not
# successful min_mic_count will be set to zero and the exit status is 1.
function mic_coprocessor_count_cluster_min() {
    local nodefile=$1
    local prefix=$2

    min_mic_count=0

    _arch_token

    local pdsh="${prefix}/../../../bin/${_arch_token}/pdsh"
    local self="${prefix}/../../functions"

    if [ ! -f "$pdsh" ] ; then
        _stderr "could not find pdsh"
        return 1
    fi

    if [ ! -f "$self" ] ; then
        _stderr "could not find functions"
        return 1
    fi

    local mic_count=`$pdsh -N -w ^$nodefile '/sbin/lspci -x | grep -c "Co-processor: Intel"' | sort | head -n 1`
    if [[ $? == 0 && -n ${mic_count} && ${mic_count} =~ ^-?[0-9]+$ ]] ; then
          min_mic_count=${mic_count}
          return 0
    fi

    _stderr "could not determine if Intel(R) Xeon Phi(TM) coprocessors were installed."
    return 1
}

# Defines a variable named $num_physical_cores that contains the
# number of physical (not logical) cores.  If not successful,
# $num_physical_cores = 0 and the exit status is 1.
function num_physical_cores() {
    local ncores=`lscpu -p=core | grep -v "^#" | sort -u | wc -l`
    if [[ $? == 0 && -n ${ncores} ]] ; then
        num_physical_cores=$ncores
        return 0
    fi

    _stderr "could not determine the number of physical cores"
    return 1
}

# Defines a variable named $num_physical_cores_cluster_min that
# contains the minimum number of physical cores across a set of nodes.
# If not successful,$num_physical_cores_cluster_min = 0 and the exit
# status is 1.
function num_physical_cores_cluster_min() {
    local nodefile=$1
    local prefix=$2
    num_physical_cores_cluster_min=0

    _arch_token

    local pdsh="${prefix}/../../../bin/${_arch_token}/pdsh"
    local self="${prefix}/../../functions"

    if [ ! -f "$pdsh" ] ; then
        _stderr "could not find pdsh"
        return 1
    fi

    if [ ! -f "$self" ] ; then
        _stderr "could not find functions"
        return 1
    fi

    local ncores=`$pdsh -N -w ^$nodefile ". $self && num_physical_cores && echo \\\$num_physical_cores" | sort -un | head -1`
    if [[ $? == 0 && -n ${ncores} && ${ncores} =~ ^[0-9]+$ ]] ; then
        num_physical_cores_cluster_min=$ncores
        return 0
    fi

    _stderr "could not determine the minimum cluster number of physical cores"
    return 1
}

# Setup the Intel(R) MPI Library shell environment.  The exit status
# is 0 if successful, 1 otherwise.  First tries I_MPI_ROOT, then
# /opt/intel/impi/latest, and if that does not exist, tries
# /opt/intel/impi/x.y.z where x.y.z is the largest (i.e., latest)
# value if multiple versions are installed.  Exports CLCK_I_MPI_ROOT
# to the environment used.
function mpivars() {
    local base="/opt/intel/impi"

    _arch_token

    local mpivars=""

    if [ ! -z ${I_MPI_ROOT+x} ] ; then
        # MPI environment is already defined, use it.
        mpivars="${I_MPI_ROOT}/${_arch_token}/bin/mpivars.sh"
        CLCK_I_MPI_ROOT="${I_MPI_ROOT}"
    elif [ -e "${base}/latest/${_arch_token}/bin/mpivars.sh" ] ; then
        # /opt/intel/impi/latest exists, use it.
        mpivars="${base}/latest/${_arch_token}/bin/mpivars.sh"
        CLCK_I_MPI_ROOT="${base}/latest"
    else
        # look for the latest version in /opt/intel/impi.
        # looks for ${base}/1.2.3.4 and converts it to 1.2.3.4
        local versions=`\find ${base} -maxdepth 1 -regex "${base}/[0-9\.]*" -print 2> /dev/null | awk -F/ '{print $5}'`
        if [[ "$versions" == "" ]] ; then
            _stderr "no version of Intel(R) MPI Library found"
            return 1
        fi

        local maxver="0.0.0"
        for version in ${versions}
        do
            _vercmp $version $maxver
            if [ $? == 1 ] ; then
                maxver=$version
            fi
        done

        mpivars="${base}/${maxver}/${_arch_token}/bin/mpivars.sh"
        CLCK_I_MPI_ROOT="${base}/${maxver}"
    fi

    if [ -e ${mpivars} ] ; then
        source ${mpivars}
        return 0
    fi

    _stderr "unable to setup Intel(R) MPI Library environment"
    return 1
}

########
# All functions below this point are prefixed with an underscore.
# This denotes that the functions are private and not intended to be
# used outside this file.  Warning: these functions may change without
# warning.
########

# For the architecture, return the corresponding token used by Intel
# tools, x86_64 -> intel64, k1om -> mic.
function _arch_token() {
    local arch=`uname -m`
    _arch_token="intel64"

    case "$arch" in
        "k1om")
            _arch_token="mic"
            ;;
        "x86_64")
            _arch_token="intel64"
            ;;
        *)
            _stderr "Unrecognized architecture, assuming intel64"
            return 1;
            ;;
    esac

    return 0
}

# Echo to STDERR.
function _stderr() {
    echo $* >&2
}

# Compare two version strings of the format a.b.c.d.  Returns 1 if the
# first version is greater, 0 if it less or the same.
function _vercmp() {
    local ver1=`echo $1 | awk -F. '{printf "%03d%03d%03d%03d\n", $1, $2, $3, $4}'`
    local ver2=`echo $2 | awk -F. '{printf "%03d%03d%03d%03d\n", $1, $2, $3, $4}'`

    if [ $ver1 -gt $ver2 ] ; then
        return 1
    else
        return 0
    fi
}
