#!/bin/sh -e

# TODO Cleanup non-libgccjit items.

sys_arch=${3:-$(uname -m)}

sed_i() {
    for file; do :; done
    sed "$@" > _
    cat _ > "$file"
                     rm -f _
}

if [ "${sys_arch#i*86}" ]; then
    # Do not create lib64 directories
    sed_i '/m64=/s/lib64/lib/' gcc/gcc/config/i386/t-linux64
    sed_i 's/lib64/lib/'       gcc/gcc/config/i386/linux64.h
fi

# FIXME: there is an offset on the diff, causing 'busybox patch' to fail.
(   
    cd gcc
         patch -p1 < ../gccjit-musl-fix.patch
)

case "$sys_arch" in
    i*86)   archopts="--build=i686-pc-linux-musl" ;;
    x86_64) archopts="--build=x86_64-pc-linux-musl" ;;
esac

# Build must happen outside of gcc source.
mkdir -p gcc-build
cd gcc-build

export libat_cv_have_ifunc=no

../gcc/configure \
    --prefix=/usr \
    "$archopts" \
    --disable-bootstrap \
    --disable-fixed-point \
    --disable-libada \
    --disable-libquadmath \
    --disable-libsanitizer \
    --disable-libssp \
    --disable-libvtv \
    --disable-lto \
    --disable-multilib \
    --disable-nls \
    --disable-symvers \
    --disable-werror \
    --enable-__cxa_atexit \
    --enable-checking=release \
    --enable-default-pie \
    --enable-default-ssp \
    --enable-host-shared \
    --enable-languages=jit \
    --enable-shared \
    --enable-threads \
    --enable-tls \
    --mandir=/usr/share/man \
    --with-system-zlib \
    --without-included-gettext

make
make DESTDIR="$1" -C gcc install 

# Remove unnecessary gcc files.
rm -rf "$1/usr/bin" \
       "$1/usr/lib/gcc" \
       "$1/usr/libexec" \
       "$1/usr/share/man"

# Remove info pages other than libgccjit
find "$1/usr/share/info" -type f ! -name libgccjit.info -exec rm -f {} +
