#!/bin/bash
set -e

# Install deps
apt update
DEBIAN_FRONTEND=noninteractive apt install -y git wget make gcc g++ curl cmake clang meson libssl-dev libsgx-dcap-quote-verify-dev libcurl4-openssl-dev

# Download and install Intel SDK
cd /opt/intel
wget https://download.01.org/intel-sgx/sgx-linux/2.18/distro/ubuntu20.04-server/sgx_linux_x64_sdk_2.18.100.3.bin
chmod +x sgx_linux_x64_sdk_2.18.100.3.bin
echo yes | ./sgx_linux_x64_sdk_2.18.100.3.bin
rm -f sgx_linux_x64_sdk_2.18.100.3.bin

# Clone and Build QVL
cd /app
git clone --single-branch -b DCAP_1.15 https://github.com/intel/SGXDataCenterAttestationPrimitives.git
cd /app/SGXDataCenterAttestationPrimitives/QuoteVerification/QVL/Src
./release

# Clone and Download mbedtls lib
cd /app
git clone --single-branch -b v1.3.1 https://github.com/gramineproject/gramine.git
cd /app/gramine
meson subprojects download

# Clone and Build NAPI Stubs
cd /app
git clone --single-branch -b main https://github.com/napi-bindings/node-api-stub.git
cd /app/node-api-stub
git checkout a253cf6
mkdir ./build
cmake -DCMAKE_BUILD_TYPE=Release -G "Unix Makefiles" -S ./ -B ./build
cmake --build ./build

# Install nodejs
curl -sL https://deb.nodesource.com/setup_16.x | bash -
DEBIAN_FRONTEND=noninteractive apt install -y nodejs

# Build addon
cd /app/src/
export GRAMINE_PATH=/app/gramine
export SGX_PRIMITIVES=/app/SGXDataCenterAttestationPrimitives
export NODE_API_STUB=/app/node-api-stub/build

npm i -g node-addon-api node-gyp nan
MBEDTLS=$(find ${GRAMINE_PATH}/subprojects/mbedtls* -maxdepth 0 -type d)
if [ $? -eq 0 ]; then
    MBEDTLS=$(find ${MBEDTLS}/mbedtls* -maxdepth 0 -type d)
    if [ $? -eq 0 ]; then
    echo "MBEDTLS found in ${MBEDTLS}"
    export MBEDTLS=${MBEDTLS}
    else
        echo "MBEDTLS not found"
        exit 1
    fi
else
    echo "MBEDTLS not found"
    exit 1
fi

export NODE_PATH=$(npm root -g)

rm -rf /app/src/build
npx node-gyp configure build
strip ./build/Release/sgx_native.node

BUILD_DIR=/app/src/build/Release
cp /usr/lib/x86_64-linux-gnu/libmbedcrypto_gramine.so.12 ${BUILD_DIR}
cp /usr/lib/x86_64-linux-gnu/libmbedx509_gramine.so.4 ${BUILD_DIR}
cp /usr/lib/x86_64-linux-gnu/libsgx_dcap_quoteverify.so.1 ${BUILD_DIR}
cp /usr/lib/x86_64-linux-gnu/libsgx_util.so ${BUILD_DIR}
cp /usr/lib/x86_64-linux-gnu/libcjson.so.1 ${BUILD_DIR} #only for tests

# libsgx_default_qcnl_wrapper.so.1 and libdcap_quoteprov.so.1 installed with the package libsgx_dcap_default_qpl

#TODO: CHECK NEXT LIBS
#libsgx_urts.so.1
