abinfo "Shadow build to ensure sanity..."
mkdir -pv "$SRCDIR"/build
cd "$SRCDIR"/build

# Linker environment definition.
echo "slibdir=/usr/lib" >> "$SRCDIR"/configparms
echo "rtlddir=/usr/lib" >> "$SRCDIR"/configparms
echo "sbindir=/usr/bin" >> "$SRCDIR"/configparms
echo "rootsbindir=/usr/bin" >> "$SRCDIR"/configparms

# Frame pointers shouldn't be omitted for glibc
# Hardening should not be enabled at build time.
# -fPIC for libraries.
export CFLAGS="${CFLAGS/-fomit-frame-pointer/}"
export CFLAGS="${CFLAGS/-fstack-protector-strong/} -fPIC"
export CXXFLAGS="${CFLAGS/-fstack-protector-strong/} -fPIC"
export CPPFLAGS="${CPPFLAGS/-D_FORTIFY_SOURCE=2/}"
export LDFLAGS="${LDFLAGS} -fPIC"

# Thumb build of glibc fails.
export CFLAGS="${CFLAGS/-mthumb/}"
export CXXFLAGS="${CXXFLAGS/-mthumb/}"

abinfo "Configuration (parameters in autobuild/defines)..."
"$SRCDIR"/configure \
    ${AUTOTOOLS_DEF[@]} \
    ${AUTOTOOLS_AFTER[@]}

# Do not build programs/utilities for now, to avoid non-hardened programs.
echo "build-programs=no" >> "$SRCDIR"/configparms

# Re-enable hardening for GLibc utilities.
sed -e "/build-programs=/s#no#yes#" \
    -i "$SRCDIR"/configparms

abinfo "Building GNU C Library..."
make

abinfo "Initialising linker cache configuration directory ..."
mkdir -pv "$PKGDIR"/etc/ld.so.conf.d

abinfo "Installing runtime and files..."
make install \
    install_root="$PKGDIR"

abinfo "Removing upstream ld.so cache ..."
rm -v "$PKGDIR"/etc/ld.so.cache

abinfo "Installing systemd supplements for NSCD..."
install -dvm755 "$PKGDIR"/usr/lib/{locale,systemd/system,tmpfiles.d}
install -vm644 "$SRCDIR"/nscd/nscd.conf \
    "$PKGDIR"/etc/nscd.conf
install -vm644 "$SRCDIR"/nscd/nscd.service \
    "$PKGDIR"/usr/lib/systemd/system
install -vm644 "$SRCDIR"/nscd/nscd.tmpfiles \
    "$PKGDIR"/usr/lib/tmpfiles.d/nscd.conf

abinfo "Installing "getaddrinfo" configuration file..."
install -vm644 "$SRCDIR"/posix/gai.conf \
    "$PKGDIR"/etc/gai.conf

abinfo "Creating a compatibility symlink to ld-$PKGVER.so ..."
cd "$PKGDIR"/usr/lib
ln -sv ld* \
    ld-$PKGVER.so

abinfo "Pre-generating Locale definition archive..."
make -C "$SRCDIR"/build localedata/install-locales \
    install_root="$PKGDIR"

abinfo "Installing locale-gen and configuration files..."
sed -r \
    -e '1,3d' \
    -e 's|/| |g' \
    -e 's| ?\\||g' \
    -e 's|^|#|g' \
    -e 's|^#([^ ]*) UTF-8|\1 UTF-8|' \
    "$SRCDIR"/localedata/SUPPORTED >> "$SRCDIR"/../locale-gen-$LOCALEGENVER/locale.gen
install -Dvm644 "$SRCDIR"/../locale-gen-$LOCALEGENVER/locale.gen \
    "$PKGDIR"/etc/locale.gen
install -Dvm644 "$SRCDIR"/../locale-gen-$LOCALEGENVER/locale.gen \
    "$SRCDIR"/locale.gen
install -Dvm755 "$SRCDIR"/../locale-gen-$LOCALEGENVER/locale-gen \
    "$PKGDIR"/usr/bin/locale-gen
