#!/usr/bin/env bash

# Create $product_dir/ups/mkl.{table,cfg} for Intel Math Kernel Library
# usage:
#   create-ups-for-mkl.sh PATH_TO_MKL product_dir

set -e

PATH_TO_MKL="$1"
product_dir="$2"

if [[ ! -d "$PATH_TO_MKL" || -z "$product_dir" ]]
then
    echo "$(basename "$0"): invalid command line" 1>&2
    exit 1
fi

pushd "$PATH_TO_MKL"
PATH_TO_MKL="$PWD"
popd

MKL_DIR=( $(find "$PATH_TO_MKL" -path "*/mkl/include") )
MKL_LIB=( $(find "$PATH_TO_MKL" -path "*/intel64/libmkl_core.so") )
ICC_LIB=( $(find "$PATH_TO_MKL" -path "*/intel64/libiomp5.so") )

if [[ -z "$MKL_DIR" || -z "$MKL_LIB" || -z "ICC_LIB" ]]
then
    echo "MKL not found." 1>&2
    exit 1
fi

MKL_DIR="$(dirname "$(dirname "$MKL_DIR")")"
MKL_LIB="$(dirname "$MKL_LIB")"
ICC_LIB="$(dirname "$ICC_LIB")"

mkdir -p "$product_dir/ups"

{
    echo '# MKL_SYSTEM_DIR points to the system-installed location.'
    echo '# MKL_SYSTEM_LIBS are the library locations.'
    echo '# These two are used by mkl.cfg'
    echo ''
    echo "envSet(MKL_SYSTEM_DIR, $MKL_DIR)"
    echo "envPrepend(MKL_SYSTEM_LIBS, $ICC_LIB)"
    echo "envPrepend(MKL_SYSTEM_LIBS, $MKL_LIB)"
    echo "envPrepend(LD_LIBRARY_PATH, \${MKL_SYSTEM_LIBS})"
} > "$product_dir/ups/mkl.table"

cat > "$product_dir/ups/mkl.cfg" << 'EOF'
# -*- python -*-

import lsst.sconsUtils
import os
import os.path
import re

dependencies = {
    "required": [],
}

class MklConfiguration(lsst.sconsUtils.ExternalConfiguration):
    def __init__(self, *args, **kwargs):
        super(MklConfiguration, self).__init__(*args, **kwargs)
        sysDir = os.getenv("MKL_SYSTEM_DIR")
        sysLibs = os.getenv("MKL_SYSTEM_LIBS")
        if sysDir is None or sysLibs is None:
            raise RuntimeError("MKL_SYSTEM_DIR and MKL_SYSTEM_LIBS not set")
        self.paths["CPPPATH"] = [ os.path.join(sysDir, 'mkl', 'include') ]
        self.paths["LIBPATH"] = re.split(":", sysLibs)

config = MklConfiguration(
    __file__,
    headers=["mkl_lapack.h"],
    libs=['mkl_intel_lp64', 'mkl_intel_thread', 'mkl_core', 'iomp5', 'pthread'],
)
EOF
