#!/usr/bin/env bash
#
# Copyright (C) 2011-2017 Intel Corporation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in
#     the documentation and/or other materials provided with the
#     distribution.
#   * Neither the name of Intel Corporation nor the names of its
#     contributors may be used to endorse or promote products derived
#     from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#

set -e

PKG_NAME="Intel SGX SDK"

select_install_path()
{
    USER_INPUT_PATH=$(pwd)
    echo
    echo -n "Do you want to install in current directory? [yes/no] : "
    read ANSWER

    if [ "$ANSWER" == "yes" ]; then
        if [ ! -d "$USER_INPUT_PATH" ] || [ ! -w "$USER_INPUT_PATH" ]; then
            echo "Can not install in $USER_INPUT_PATH, please check the permission!"
            exit 4
        fi
    else
        echo
        echo -n "Please input the directory which you want to install in : "
        read USER_INPUT_PATH

        eval USER_INPUT_PATH="$USER_INPUT_PATH"

        if [ -d "$USER_INPUT_PATH" ]; then
            if [ ! -w "$USER_INPUT_PATH" ]; then
                echo "Can not install in $USER_INPUT_PATH, please check the permission!"
                exit 4
            fi
        else
            mkdir -p "$USER_INPUT_PATH"
            if [ "$?" != "0" ]; then
                echo "Can not install in $USER_INPUT_PATH, please check the permission!"
                exit 4
            fi
        fi
    fi
}


prev=
for option
do
  if test -n "$prev"; then
    eval $prev=\$option
    prev=
    continue
  fi

  case $option in
  *=?*) optarg=`expr "X$option" : '[^=]*=\(.*\)'` ;;
  *=)   optarg= ;;
  *)    optarg=yes ;;
  esac

  case $option in
  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
    prev=prefix ;;
  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
    prefix=$optarg ;;

  esac
done

if [ -n "$prefix" ]; then
    eval USER_INPUT_PATH="$prefix"

    if [ -d "$USER_INPUT_PATH" ]; then
        if [ ! -w "$USER_INPUT_PATH" ]; then
            echo "Can not install in $USER_INPUT_PATH, please check the permission!"
            exit 4
        fi
    else
        mkdir -p "$USER_INPUT_PATH"
        if [ "$?" != "0" ]; then
            echo "Can not install in $USER_INPUT_PATH, please check the permission!"
            exit 4
        fi
    fi
else
    select_install_path
fi

USER_INPUT_PATH=$(cd "$USER_INPUT_PATH"; pwd -P)

PATH=/usr/bin:/bin
umask 022

SDKPKG=`mktemp -t sgx-sdk-pkg.XXXXXX`
SDK_TEMP_FOLDER=`mktemp -d sgx-sdk-XXXXXX -p /tmp`
trap "rm -rf $SDKPKG $SDK_TEMP_FOLDER 2>/dev/null; exit 3" HUP INT QUIT TERM

# The number of lines in this script (plus 1).  Using this number to
# calculate the start address of the payload.
NR_SCRIPT_LINES=@linenum@

# Run /usr/bin/md5sum on the binary payload to get the MD5 check sum.
CHKSUM=@md5sum@

# Get the install payload from this shell script.
echo -n "Unpacking $PKG_NAME ..."
tail -n +$NR_SCRIPT_LINES "$0" > $SDKPKG
echo " done."

echo -n "Verifying the integrity of the install package ..."
if test $(md5sum $SDKPKG | awk '{print $1}') != $CHKSUM; then
    echo " The install package appears to be corrupted."
    exit 1
fi
echo " done."

echo -n "Installing $PKG_NAME ..."
tar zxf $SDKPKG -C $SDK_TEMP_FOLDER >/dev/null 2>&1
retcode=$?			# Save the return code
# Clean-up the temporary tarball.
rm -f $SDKPKG 2>/dev/null

if test $retcode -ne 0; then
    echo " failed."
    exit 2
fi
echo " done."

pushd ${SDK_TEMP_FOLDER}

sed -i "s#\(SGX_PACKAGES_PATH=\).*#\1$USER_INPUT_PATH#" scripts/installConfig
source scripts/installConfig
make install INSTALLER_FORM=BIN

popd

${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/scripts/install.sh BIN

rm -fr ${SDK_TEMP_FOLDER}

export_the_simulation()
{
    if [ ! -d ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs ]; then
        mkdir ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs
    else
        rm -f ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs/libsgx_urts_sim.so
        rm -f ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs/libsgx_uae_service_sim.so
    fi
    ln -s ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/${LIB_DIR}/libsgx_urts_sim.so ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs/ 
    ln -s ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/${LIB_DIR}/libsgx_uae_service_sim.so ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/sdk_libs/ 
} 

generate_environment_script()
{
    cat > ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/environment <<EOF
export SGX_SDK=${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}
export PATH=\$PATH:\$SGX_SDK/$(dirname ${BIN_DIR}):\$SGX_SDK/${BIN_DIR}
export PKG_CONFIG_PATH=\$PKG_CONFIG_PATH:\$SGX_SDK/pkgconfig
if [ -z "\$LD_LIBRARY_PATH" ]; then
     export LD_LIBRARY_PATH=\$SGX_SDK/sdk_libs
else
     export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:\$SGX_SDK/sdk_libs
fi

EOF
}

export_the_simulation
generate_environment_script

echo """
Please set the environment variables with below command:
"
echo -e "\033[32;49;1msource ${SGX_PACKAGES_PATH}/${SDK_PKG_NAME}/environment\033[39;49;0m"

exit 0
