pkgname="gcc"
pkgver="15.2.0"
pkgdesc="The GNU Compiler Collection (PGO+LTO rebuild)"
homepage="https://gcc.gnu.org"
sources=("${pkgname}-${pkgver}.tar.xz")
urls=("https://ftp.gnu.org/gnu/gcc/${pkgname}-${pkgver}/${sources[0]}")
md5sums=("b861b092bf1af683c46a8aa2e689a6fd")

export GCC_BOOT_CFLAGS="-march=native -O2 -pipe -flto=auto"
export GCC_BOOT_LDFLAGS="-Wl,-O1 -Wl,--as-needed -flto=auto"
export GCC_MAKE_JOBS="${PARALLEL_JOBS}"

src_prepare() {
  tar -xf "${distdir}/${sources[0]}" --strip-components=1
  case $(uname -m) in
    x86_64)
      sed -e '/m64=/s/lib64/lib/' -i.orig gcc/config/i386/t-linux64
    ;;
  esac
}

src_build() {
  leaf_clear_flags

  export CFLAGS="-march=native -O2 -pipe"
  export CXXFLAGS="${CFLAGS}"
  export LDFLAGS="-Wl,-O1 -Wl,--as-needed"

  mkdir -v build
  pushd build > /dev/null

  ../configure --prefix=/usr            \
               LD=ld                    \
               --enable-languages=c,c++ \
               --enable-bootstrap       \
               --enable-lto             \
               --enable-default-pie     \
               --enable-default-ssp     \
               --enable-host-pie        \
               --disable-multilib       \
               --disable-fixincludes    \
               --with-system-zlib

  make -j"${GCC_MAKE_JOBS}" \
       BOOT_CFLAGS="${GCC_BOOT_CFLAGS}" \
       BOOT_CXXFLAGS="${GCC_BOOT_CFLAGS}" \
       BOOT_LDFLAGS="${GCC_BOOT_LDFLAGS}" \
       profiledbootstrap

  popd > /dev/null
}

src_check() {
  pushd build > /dev/null
  ulimit -s -H unlimited

  sed -e '/cpython/d' -i ../gcc/testsuite/gcc.dg/plugin/plugin.exp

  chown -R leaf .
  su leaf -c "PATH=$PATH make -k check"
  ../contrib/test_summary | grep -A7 Summ
  popd > /dev/null
}

src_install() {
  pushd build > /dev/null
  make DESTDIR="$pkgdir" install

  chown -R root:root \
    "$pkgdir"/usr/lib/gcc/$(${pkgdir}/usr/bin/gcc -dumpmachine)/${pkgver}/include{,-fixed}

  ln -sv ../bin/cpp "$pkgdir"/usr/lib
  ln -sv gcc.1 "$pkgdir"/usr/share/man/man1/cc.1

  install -d -v -m755 "$pkgdir/usr/lib/bfd-plugins"
  ln -sfv ../../libexec/gcc/$(${pkgdir}/usr/bin/gcc -dumpmachine)/${pkgver}/liblto_plugin.so \
        "$pkgdir"/usr/lib/bfd-plugins/

  mkdir -pv "$pkgdir"/usr/share/gdb/auto-load/usr/lib
  mv -v "$pkgdir"/usr/lib/*gdb.py "$pkgdir"/usr/share/gdb/auto-load/usr/lib

  popd > /dev/null
}

