#!/bin/sh

#
# Build GCC with support for offloading to NVIDIA GPUs.
#

clear

work_dir="/home/uig13265/offload/wrk"
install_dir="/home/uig13265/offload/install"

# Location of the installed CUDA toolkit
cuda_dir="/usr/local/cuda-12.2"
cuda_include="/usr/local/cuda-12.2/include"
cuda_libs="/usr/local/cuda-12.2/lib64"

# Init dirs
mkdir -p "$install_dir"
mkdir -p "$work_dir"
rm -rf "$install_dir"/*
rm -rf "$work_dir"/build-*
# async rm in cygwin
sleep 1


cd "$work_dir"

rm ./gcc/newlib

export PREFIX="$install_dir"

mkdir -p "$PREFIX/bin"
export PATH="$PREFIX/bin:$PATH"

mkdir build-binutils
cd build-binutils
../binutils/configure \
    --build=x86_64-pc-linux-gnu \
    --host=x86_64-pc-linux-gnu \
    --target=x86_64-pc-linux-gnu \
    --prefix="$PREFIX" \
    --disable-nls
make -j8 || exit 1
make install || exit 1
cd ..

# The $PREFIX/bin dir _must_ be in the PATH. We did that above.
which -- $TARGET-as || echo $TARGET-as is not in the PATH

mkdir build-nvptx-tools
cd build-nvptx-tools
../nvptx-tools/configure \
    --with-cuda-driver="$cuda_dir" \
    --prefix="$PREFIX"
make -j8 || exit 1
make install || exit 1
cd ..

ln -s ./nvptx-newlib/newlib ./gcc/newlib

mkdir build-gcc-nvptx
cd build-gcc-nvptx
../gcc/configure \
    --build=x86_64-pc-linux-gnu \
    --host=x86_64-pc-linux-gnu \
    --target=nvptx-none \
    --with-build-time-tools="$PREFIX/nvptx-none/bin" \
    --enable-as-accelerator-for=x86_64-pc-linux-gnu \
    --enable-languages="c,c++" \
    --disable-sjlj-exceptions \
    --enable-newlib-io-long-long \
    --prefix="$PREFIX"
make -j8 || exit 1
make install || exit 1
cd ..

rm ./gcc/newlib

mkdir build-gcc-acc
cd build-gcc-acc
../gcc/configure \
    --build=x86_64-pc-linux-gnu \
    --host=x86_64-pc-linux-gnu \
    --target=x86_64-pc-linux-gnu \
    --prefix="$PREFIX" \
    --enable-offload-targets=nvptx-none="$PREFIX/nvptx-none" \
    --with-cuda-driver="$cuda_dir" \
    --disable-nls \
    --enable-languages="c,c++,lto"
make -j8 || exit 1
make install || exit 1
cd ..

exit
