#!/usr/bin/env bash
# Copyright (c) Open Enclave SDK contributors.
# Licensed under the MIT License.

script=$(readlink -f "$0")
script_path=$(dirname "$script")
curr_path=$(pwd)
bin_name="lvi_mitigation_bin"
read -rp "Do you want to install in current directory? [yes/no]: " ans
if [[ "$ans" == "yes" ]]; then
  install_path="$curr_path"
else
  read -rp "Please input the directory which you want to install in: " install_path
fi

if [[ "$install_path" == "" ]]; then
  install_path="$curr_path"
fi

bin_path="$install_path"/"$bin_name"

mkdir -p "$bin_path"

clang=$(which clang-7)
clangcpp=$(which clang++-7)
if [ "$clang" ] && [ "$clangcpp" ]; then
  ln -sf "$clang" "$bin_path"/clang-7_symlink
  ln -sf "$clangcpp" "$bin_path"/clang++-7_symlink
  rm -f "$bin_path"/clang-7
  cp "$script_path"/clang-7-lvi "$bin_path"/clang-7
  rm -f "$bin_path"/clang++-7
  cp "$script_path"/clang++-7-lvi "$bin_path"/clang++-7
fi

gcc=$(which gcc)
gcpp=$(which g++)
if [ "$gcc" ] && [ "$gcpp" ]; then
  ln -sf "$gcc" "$bin_path"/gcc_symlink
  ln -sf "$gcpp" "$bin_path"/g++_symlink
  rm -f "$bin_path"/gcc
  cp "$script_path"/gcc-lvi "$bin_path"/gcc
  rm -f "$bin_path"/g++
  cp "$script_path"/g++-lvi "$bin_path"/g++
fi

# Obtain `as` and `ld` from Intel site.
intel_site="https://download.01.org/intel-sgx/sgx-linux/"
intel_tool_version="2.9"
intel_tarball="as.ld.objdump.gold.r1.tar.gz"
wget "$intel_site"/"$intel_tool_version"/"$intel_tarball" -O /tmp/"$intel_tarball"
tar -xf /tmp/"$intel_tarball" -C /tmp

intel_extract_path=external/toolset
rm -f "$bin_path"/as
cp /tmp/"$intel_extract_path"/as "$bin_path"/as
# The `ld` depends on glibc version 2.27.
glibc_version=$(ldd --version | awk '/ldd/{print $NF}')
# shellcheck disable=SC2072
if [[ "$glibc_version" > "2.26" ]]; then
  rm -f "$bin_path"/ld
  cp /tmp/"$intel_extract_path"/ld "$bin_path"/ld
fi

echo "Installed: $bin_path"
