#! /bin/bash

# Note: The test suite run address sanitizer tests. In the current mariux64 environment
# this requires
#
#     sudo sysctl vm.overcommit_memory=0

PKG=gcc
VERSION=4.5.1
BUILD=0
URL=http://ftp.gnu.org/gnu/gcc/gcc-${VERSION}/gcc-${VERSION}.tar.gz

. /pkg/texinfo-4.13a-0/profile

PREFIX=/pkg/$PKG-$VERSION-$BUILD
if [ -n "$TESTING" ]; then PREFIX=/dev/shm/$PKG-$VERSION-$BUILD ; fi

set -xe
umask 022

BUILD_TMPDIR=/dev/shm/$PKG-$VERSION-$BUILD.build.tmp
test -d $BUILD_TMPDIR && ( chmod -R u+rwx $BUILD_TMPDIR || true ; rm -rf $BUILD_TMPDIR )
mkdir -p $BUILD_TMPDIR/home
export TMPDIR=$BUILD_TMPDIR
export HOME=$BUILD_TMPDIR/home

exec </dev/null

mkdir -p $PREFIX
cat >$PREFIX/profile <<-EOF
	PATH=$PREFIX/bin:\$PATH
	if [ -d $PREFIX/.compatlibs ]; then export LD_LIBRARY_PATH=$PREFIX/.compatlibs\${LD_LIBRARY_PATH:+:\$LD_LIBRARY_PATH} ; fi
EOF
. $PREFIX/profile

export MAKEFLAGS="-j $(nproc)"

BUILDDIR=$PREFIX/build

mkdir -p $BUILDDIR
cd $BUILDDIR

test -e gcc-${VERSION}.tar.gz || wget $URL
test -d gcc-$VERSION          || tar xvf gcc-${VERSION}.tar.gz
cd gcc-$VERSION

patch -N -p 1 <<__EOF__ || true
From 146285bd5724fe602df2ea2d171dd3f0cfc425a8 Mon Sep 17 00:00:00 2001
From: Donald Buczek <buczek@molgen.mpg.de>
Date: Thu, 23 Apr 2020 17:19:31 +0200
Subject: [PATCH] i386/linux-unwind.h: Remove struct ucontext

With glibc 2.26, the "struct ucontext" definition was removed [1].

Replace with ucontext_t so we can compile with glibc >=2.26.

[1]: https://sourceware.org/glibc/wiki/Release/2.26#Removal_of_.27struct_ucontext.27
---
 gcc/config/i386/linux-unwind.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/gcc/config/i386/linux-unwind.h b/gcc/config/i386/linux-unwind.h
index 36ee370..061921f 100644
--- a/gcc/config/i386/linux-unwind.h
+++ b/gcc/config/i386/linux-unwind.h
@@ -47,7 +47,7 @@ x86_64_fallback_frame_state (struct _Unwind_Context *context,
   if (*(unsigned char *)(pc+0) == 0x48
       && *(unsigned long *)(pc+1) == 0x050f0000000fc0c7)
     {
-      struct ucontext *uc_ = context->cfa;
+      ucontext_t *uc_ = context->cfa;
       /* The void * cast is necessary to avoid an aliasing warning.
          The aliasing warning is correct, but should not be a problem
          because it does not alias anything.  */
-- 
2.26.2
__EOF__

mkdir -p objdir
cd objdir
$BUILDDIR/gcc-$VERSION/configure \
  --prefix=$PREFIX \
  --enable-shared \
  --enable-threads=posix \
  --enable-__cxa_atexit \
  --enable-clocale=gnu \
  --enable-languages=c \
  --disable-multilib \
  --with-system-zlib \
  --with-diagnostics-color=auto-if-env \
  --disable-libmudflap

make
(make -k check 2>&1 || true) | tee check.log
MAKEFLAGS= make install

cd $PREFIX
mkdir -vp lib
ln -sfv ${PREFIX}/bin/cpp lib/
ln -sfv gcc bin/cc

install -v -dm755 lib/bfd-plugins
ln -sfv ../../libexec/gcc/$(gcc -dumpmachine)/$VERSION/liblto_plugin.so lib/bfd-plugins/

exit