#!/bin/sh -e

# Not sure why this fixes the check for GCC, but it works...
export CC=gcc
export CXX=g++

# Disable ccache
export CCACHE_DISABLE=1

# Patch needs to be GNU patch.
mkdir -p path
ln -s "$(command -v gpatch)" "$PWD/path/patch"

export PATH="$PWD/path:$PATH"

for p in *.patch; do
    echo "[INFO] Applying $p"
    patch -p1 < "$p"
done

# This doesn't fix the build. Now it fails to find another file.
# I have no idea what is going on.
# It would be nice if openjdk just played nice.
#mkdir -p jdk/src/solaris/classes/sun/awt/org
#cd jdk/src/solaris/classes/sun/awt/org
#ln -s ../X11 xml
#cd "$OLDPWD"

sed -i '/^WARNINGS_ARE_ERRORS/ s/-Werror/-Wno-error/' \
    hotspot/make/linux/makefiles/gcc.make

jdk_prefix=/usr/lib/jvm/java-1.8-openjdk

export JAVA_HOME="/usr/lib/jvm/java-1.7-openjdk"
export PATH="$JAVA_HOME/bin:/usr/share/apache-ant/bin:$PATH"

export EXTRA_CPP_FLAGS="-std=gnu++98 -fno-delete-null-pointer-checks -fno-lifetime-dse -fno-strict-overflow"
export EXTRA_CFLAGS="-std=gnu++98 -Wno-error -fno-delete-null-pointer-checks -fno-lifetime-dse -fno-strict-overflow"

export CFLAGS="-O0 -fcommon -fno-exceptions -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64"
export CXXFLAGS="-O0 -fcommon -fno-exceptions -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64"

bash ./configure \
    --disable-ccache \
    --disable-option-checking \
    --disable-freetype-bundling \
    --enable-unlimited-crypto \
    --with-boot-jdk="$JDK_HOME" \
    --with-extra-cflags="$CFLAGS $EXTRA_CFLAGS" \
    --with-extra-cxxflags="$CXXFLAGS $EXTRA_CPP_FLAGS" \
    --with-extra-ldflags="$LDFLAGS" \
    --with-jtreg=no \
    --with-jobs=$(nproc) \
    --with-num-cores=$(nproc) \
    --with-vendor-name="KISS" \
    --with-milestone="fcs" \
    --with-freetype-lib=/usr/lib \
    --with-freetype-include=/usr/include/freetype2 \
    --with-giflib=system \
    --with-zlib=system \
    --disable-jfr

export CONFIG_SHELL=/usr/bin/bash

#sed -i "s/macosx/linux/g" jdk/make/Tools.gmk
#grep linux jdk/make/Tools.gmk
#sleep 4

unset MAKEFLAGS CFLAGS CXXFLAGS LDFLAGS
make -j1 \
    CONFIG_SITE=/dev/null
    CONFIG_SHELL=bash \
    JOBS="$(nproc)" \
    LOG=debug \
    CFLAGS_WARNINGS_ARE_ERRORS= \
    COMPILER_WARNINGS_FATAL=false \
    GIT=true \
    images

mkdir -p "$1/$jdk_prefix"
cp -a openjdk.build/j2sdk-image/* "$1/$jdk_prefix"
cp -a openjdk.build/include       "$1/$jdk_prefix"
rm -rf "$1/$jdk_prefix/src.zip"
