#!/bin/bash

# build glibc-$VERSION for ARMedslack.
# Based on the Slackware Build script by Patrick J. Volkerding 
#
# Extensively modified by Stuart Winter for ARMedslack.
# 

# Record toolchain & other info for the build log:
slackbuildinfo

# Paths to skeleton port's source & real Slackware source tree:
export CWD=$SLACKSOURCE/$PKGSERIES/$PKGNAM
export PORTCWD=$PWD

# Determine the CFLAGS for the known architectures:
case $ARCH in
   arm)       SLKCFLAGS="-g -O2 -march=armv4 -mtune=xscale -fno-strict-aliasing" 
              # ARCH_CONFARGS="--disable-sanity-checks --without-selinux --without-tls --without-__thread"  
              ARCH_CONFARGS="--without-selinux"  
              ;;
   powerpc)   SLKCFLAGS="-g -O2" ;;
   i486)      SLKCFLAGS="-O3 -march=i686 -mtune=pentium4" 
              ARCH_CONFARGS="--with-tls" ;;
esac

# Version of the Linux Kernel headers that we'll be compiling with:
HEADERSTWOSIX=2.6.27.6

# Sanity check on the version number in the install scripts:
# Don't need this for ARMedslack at the moment (only if we are maintaining our own
# copies if we were out of sync with Slackware).
#if ! grep -vq libutil-$VERSION}.so $PORTCWD/doinst.sh-glibc ; then
#   echo "FATAL:  doinst.sh scripts have wrong version numbers."
#   exit 1
#fi

# Determine patch level required & apply the patch:
function apply_patch () {
 patchfile=$1

 # Unpack if it's bzip2 or gzip:
 FTYPE=$( file $patchfile )
 if [ "$( echo $FTYPE | grep "bzip2 compressed" )" ]; then
    bzcat -f $patchfile > $TMPBUILD/$patchfile.unpacked
    patchfile=$TMPBUILD/$patchfile.unpacked
  elif [ "$( echo $FTYPE | grep "gzip compressed" )" ]; then
    zcat -f $patchfile > $TMPBUILD/$patchfile.unpacked
    patchfile=$TMPBUILD/$patchfile.unpacked
 fi

 # Most patches should not require more levels than this:
 success=0
 for (( pl=0 ; pl<=5 ; pl++ )) ; do
   echo "Patch : $patchfile , trying patch level $pl"
     patch --fuzz=20 -t --dry-run -p$pl < $patchfile > /dev/null 2>&1 && success=1 && break
   done
 if [ $success = 1 ]; then
    echo "Patch: $patchfile will apply at level $pl"
    patch --fuzz=20 --verbose -p$pl < $patchfile
    return 0
  else
    echo "Patch: $patchfile failed to apply at levels 0-5"
    return 1
 fi
}

# Extract the source:
function extractglibcsource () {
  cd $TMPBUILD
  rm -rf glibc*

  # Unpack the main from the Slackware source tree:
  echo "Unpacking main glibc source..."
  tar xf $CWD/glibc-$VERSION.tar.bz2 || failextract
  cd glibc*
  tar xf $CWD/glibc-libidn-$VERSION.tar.bz2 || failextract
  mv glibc-libidn-$VERSION libidn || exit 1
  # Unpack the ports source from ARMedslack's directory -- since it's
  # no longer included with glibc:
  echo "Unpacking glibc ports source..."
  tar xf $PORTCWD/sources/glibc-ports-$VERSION.tar.bz2 || failextract
  mv glibc-ports-$VERSION ports || exit 1
 
  # Apply Slackware-specific patches:
  #
  # Use old-style locale directories rather than a single (and strangely
  # formatted) /usr/lib/locale/locale-archive file:
  zcat $CWD/glibc.locale.no-archive.diff.gz | patch -p1 --verbose || exit 1
  # Fix NIS netgroups:
  zcat $CWD/glibc.nis-netgroups.diff.gz | patch -p1 --verbose || exit 1
  # Evidently glibc never expected Linux kernel versions to be in the
  # format 1.2.3.4.  This patch makes glibc consider the kernel version
  # to be only the first three digit groups found, and drops any
  # trailing non-digit characters:
  zcat $CWD/glibc.kernelversion.diff.gz | patch -p1 --verbose || exit 1
  # Support ru_RU.CP1251 locale:
  # zcat $CWD/glibc.ru_RU.CP1251.diff.gz | patch -p1 --verbose || exit 1
  # Fix missing MAX macro in getcwd.c:
  zcat $CWD/glibc.getcwd.max.macro.diff.gz | patch -p1 --verbose || exit 1
  # The is_IS locale is causing a strange error about the "echn" command
  # not existing.  This patch reverts is_IS to the version shipped in
  # glibc-2.5:
  zcat $CWD/is_IS.diff.gz | patch -p1 --verbose || exit 1

  # Extract the Debian diff -- this creates a 'debian' directory.  We 
  # pull ARM patches from it: 
  zcat $PORTCWD/sources/glibc_${VERSION}-*.diff.gz | patch -p1 || failpatch

  # Apply ARM specific patches: these are taken from Debian's diff.
  # We apply all of them:
  for i in debian/patches/arm/* ; do
     apply_patch $i || failpatch
  done
  # And non arm specific patches:
  # 
  # For v16 diff:
  apply_patch debian/patches/any/cvs-gcc-4.3.diff || failpatch
  apply_patch debian/patches/any/local-missing-linux_types.h.diff || failpatch
  apply_patch debian/patches/any/submitted-longdouble.diff || failpatch
  apply_patch debian/patches/any/submitted-sched_h.diff || failpatch
  apply_patch debian/patches/any/local-libgcc-compat-ports.diff || failpatch
  apply_patch debian/patches/any/cvs-sched_h.diff || failpatch
  #
  # For v9 diff - last known working version:
  #apply_patch debian/patches/any/submitted-gcc-4.3.diff || failpatch
  #apply_patch debian/patches/any/submitted-libgcc_s.so.diff || failpatch
  #apply_patch debian/patches/any/local-missing-linux_types.h.diff || failpatch
  #apply_patch debian/patches/any/submitted-longdouble.diff || failpatch
  #apply_patch debian/patches/any/submitted-sched_h.diff || failpatch

  # 
  # Apply patches from Gentoo!
  # 
  #set -x
  #mkdir -vpm755 gentoo
  #tar xvvf $PORTCWD/sources/glibc-2.7-patches-*.tar.bz2 -C gentoo/
  #apply_patch gentoo/patches/6220_all_glibc-2.4-arm-cirrus-ep93xx-maverick-crunch-fpu.patch || failpatch
  #apply_patch gentoo/patches/6230_all_arm-glibc-2.5-no-page-header.patch || failpatch
  #set +x

  # Turn off stack protector.
  # gcc 4.2.3's stack protector (libssp) on ARM produces binaries that segfault, so
  # let's turn off the stack protector feature.
  fgrep -lr -- '-fstack-protector' . | xargs sed -i 's?-fstack-protector?-fno-stack-protector?g'


# Update the timezone information, or a lot of people will be
# very unhappy...
  ( cd timezone
    tar xf $CWD/tzdata2008i.tar.gz || exit 1
    chown root:root *
    mv -fv yearistype.sh yearistype
    chmod 644 *
    chmod 755 yearistype
    mkdir -vpm755 tzcode
    cd tzcode
    tar xf $CWD/tzcode2008h.tar.gz || exit 1
    chown -R root:root .
    chmod 644 *
    cp -fav *.c *.h ..
   ) || exit 1

  # Clean up CVS mess:
  find . -type d -name CVS -print0 | xargs -0 rm -rf
  
  # Ensure permissions & ownerships:
  slackhousekeeping

  # Create a separate build directory:
  mkdir -vpm755 build_dir
  cd build_dir
}


# Temporary build locations:
export TMPBUILD=$TMP/build-$PKGNAM
# This is the initial $DESTDIR:
export PKG=$TMP/package-glibc-incoming-tree
mkpkgdirs # Delete & re-create temporary directories then cd into $TMPBUILD

# Then we'll compile the following packages from it:
PGLIBC=$TMP/package-glibc
PSOLIBS=$TMP/package-glibc-solibs
PZONE=$TMP/package-glibc-zoneinfo
PI18N=$TMP/package-glibc-i18n
PPROFILE=$TMP/package-glibc-profile
PDEBUG=$TMP/package-glibc-debug

# Empty & create these locations first:
for dir in $PKG $PGLIBC $PSOLIBS $PZONE $PI18N $PPROFILE $PDEBUG ; do
    rm -rf $dir
    mkdir -vpm755 $dir
done

# Create an incoming directory structure for glibc to be built into:
mkdir -vpm755 $PKG/{var/{run/nscd,db/nscd},lib,sbin,usr/{bin,lib,sbin,include,doc,man,share}}

# Extract our pre-made Linux Kernel include files.    
# All I did for these was extract the source, copy the config file in place and
# run make oldconfig, then tar up the include dir.
#
mkdir -vpm755 $TMPBUILD/headers2.6/
echo "Extracting Linux 2.6 Kernel headers into $TMPBUILD"
# We keep these in the d/ series.
tar xf $PORTCWD/../../d/kernel-headers/sources/kernel-headers-${HEADERSTWOSIX}.tar.bz2 -C $TMPBUILD/headers2.6/ || failextract

################# Build glibc #############################
echo "[**] Building NPTL version of glibc [**]"

# Extract, patch the source & cd into the build dir:
extractglibcsource || failextract

# Configure:
# Note: the --enable-kernel option tells glibc which obsolete options to
# compile *INTO* glibc, not what to compile out!!
CFLAGS="$SLKCFLAGS" \
../configure $ARCH_CONFARGS \
   --prefix=/usr \
   --enable-kernel=2.6.22 \
   --with-headers=$TMPBUILD/headers2.6/include \
   --enable-add-ons=libidn,nptl,ports \
   --enable-profile \
   --with-tls \
   --with-__thread \
   --without-cvs \
   --build=$ARCH-slackware-linux \
   --host=$ARCH-slackware-linux \
   --target=$ARCH-slackware-linux || failconfig

# Build:
make -j1 || failmake

# Install into local package:
make install install_root=$PKG || failinstall
make localedata/install-locales install_root=$PKG || failinstall

# The prevailing standard seems to be putting unstripped libraries in
# /usr/lib/debug/ and stripping the debugging symbols from all the other
# libraries.
mkdir -vpm755 $PKG/usr/lib/debug
cp -a $PKG/lib/l*.so* $PKG/usr/lib/debug
cp -a $PKG/usr/lib/*.a $PKG/usr/lib/debug
# Don't need debug+profile:
( cd $PKG/usr/lib/debug ; rm -f *_p.* )
# NOTE:  Is there really a reason for the glibc-debug package?
# If you're debugging glibc, you can also compile it, right?

## COMMENTED OUT:  There's no reason for profile libs to include -g information.
## Put back unstripped profiling libraries:
#mv $PKG/usr/lib/debug/*_p.a $PKG/usr/lib
# It might be best to put the unstripped and profiling libraries in glibc-debug and glibc-profile.

# I don't think "strip -g" causes the pthread problems.  It's --strip-unneeded that does.
strip -g $PKG/lib/l*.so*
strip -g $PKG/usr/lib/l*.so*
strip -g $PKG/usr/lib/lib*.a

# Back to the sources dir to add some files/docs:
cd $TMPBUILD/glibc-$VERSION

# We'll automatically install the config file for the Name Server Cache Daemon.
# Perhaps this should also have some commented-out startup code in rc.inet2...
mkdir -vpm755 $PKG/etc
cat nscd/nscd.conf > $PKG/etc/nscd.conf.new

# Install some scripts to help select a timezone:
mkdir -vpm755 $PKG/var/log/setup
install -vpm755 -oroot -groot $CWD/timezone-scripts/setup.timeconfig $PKG/var/log/setup/
mkdir -vpm755 $PKG/usr/sbin
install -vpm755 -oroot -groot $CWD/timezone-scripts/timeconfig $PKG/usr/sbin/

## Install docs:
( mkdir -vpm755 $PKG/usr/doc/glibc-$VERSION
  cp -favv \
    BUGS CONFORMANCE COPYING COPYING.LIB FAQ INSTALL LICENSES NAMESPACE \
    NEWS NOTES PROJECTS README README.libm \
    $PKG/usr/doc/glibc-$VERSION
)

# Don't forget to add the /usr/share/zoneinfo/localtime -> /etc/localtime symlink! :)
if [ ! -r $PKG/usr/share/zoneinfo/localtime ]; then
  ( cd $PKG/usr/share/zoneinfo ; ln -sf /etc/localtime . )
fi

# Start fakeroot server:
start_fakeroot

# Slackware policy:
( cd $PKG
  # root:root
  slackchown 

  # 644 docs:
  slack644docs

  # Strip most binaries:
  find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-debug 2> /dev/null
  find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip -g 2> /dev/null

  # gzip man & info pages:
  slackgzpages -i

  # This is junk
  rm -f etc/ld.so.cache
  find . -name "*.orig" -exec rm -f {} \; 

  # These contain scratchbox paths when built inside sbox:
  sed -i '1s/.*/#!\/bin\/bash/' usr/bin/xtrace usr/bin/tzselect )

##################################
# OK, time to make some packages #
##################################

# Delete old package versions?
if [ "${DELETEOLDPKGS}" = "Yes" ]; then
   rm -f $PKGSTORE/a/glibc-{zoneinfo,solibs}*
   rm -f $PKGSTORE/l/glibc-*
   rm -f $PKGSTORE/l/glibc-{debug,profile}*
#   rm -f $PKGSTORE/../extra/glibc-extra-packages/glibc-{debug,profile}*
fi

# glibc-zoneinfo.  We will start with an easy one to avoid breaking a sweat.  ;-)
cd $PZONE
# Install some scripts to help select a timezone:
mkdir -vpm755 $PZONE/var/log/setup
cp -a $CWD/timezone-scripts/setup.timeconfig $PZONE/var/log/setup
chown root:root $PZONE/var/log/setup/setup.timeconfig
chmod 755 $PZONE/var/log/setup/setup.timeconfig
mkdir -vpm755 $PZONE/usr/sbin
cp -a $CWD/timezone-scripts/timeconfig $PZONE/usr/sbin
chown root:root $PZONE/usr/sbin/timeconfig
chmod 755 $PZONE/usr/sbin/timeconfig
mkdir -vpm755 $PZONE/install
install -vpm644 -oroot -groot $CWD/doinst.sh-glibc-zoneinfo $PZONE/install/doinst.sh
install -vpm644 -oroot -groot $CWD/slack-desc.glibc-zoneinfo $PZONE/install/slack-desc
mkdir -vpm755 $PZONE/usr/share
cd $PZONE/usr/share
cp -a --verbose $PKG/usr/share/zoneinfo .
cd $PZONE
mkdir -vpm755 $PZONE/etc
# This is already hard-coded into doinst.sh (like it'll be there anyway ;-):
rm -f etc/localtime
# Wrap it up:
makepkg -l y -c n $PKGSTORE/a/glibc-zoneinfo-$VERSION-noarch-$BUILD.tgz

# glibc-profile:
mkdir -vpm755 $PPROFILE/usr/lib
cd $PPROFILE
# Might as well just grab these with 'mv' to simplify things later:
mv $PKG/usr/lib/lib*_p.a usr/lib
# Profile libs should be stripped.  Use the debug libs to debug...
( cd usr/lib ; strip -g *.a )
mkdir -vpm755 install
install -vpm644 -oroot -groot $CWD/slack-desc.glibc-profile install/slack-desc
#makepkg -l y -c n $PKGSTORE/../extra/glibc-extra-packages/glibc-profile-$VERSION-$PKGARCH-$BUILD.tgz
makepkg -l y -c n $PKGSTORE/l/glibc-profile-$VERSION-$PKGARCH-$BUILD.tgz

# THIS IS NO LONGER PACKAGED (or is it?  might be better to let it be made, and then ship it or not...)
# glibc-debug:
cd $PDEBUG
mkdir -vpm755 usr/lib
# Might as well just grab these with 'mv' to simplify things later:
mv $PKG/usr/lib/debug usr/lib
mkdir -vpm755 install
install -m644 -oroot -groot $CWD/slack-desc.glibc-debug install/slack-desc
makepkg -l y -c n $TMPBUILD/glibc-debug-$VERSION-$PKGARCH-$BUILD.tgz
## INSTEAD, NUKE THESE LIBS
#rm -rf $PKG/usr/lib/debug
#makepkg -l y -c n $PKGSTORE/../extra/glibc-extra-packages/glibc-debug-$VERSION-$PKGARCH-$BUILD.tgz

# glibc-i18n:
cd $PI18N
mkdir -vpm755 usr/lib
rm -rf usr/lib/locale
cp -a $PKG/usr/lib/locale usr/lib
mkdir -vpm755 usr/share
cp -a $PKG/usr/share/i18n usr/share
cp -a $PKG/usr/share/locale usr/share
mkdir -vpm755 install
install -m644 -oroot -groot $CWD/slack-desc.glibc-i18n install/slack-desc
makepkg -l y -c n $PKGSTORE/l/glibc-i18n-$VERSION-noarch-$BUILD.tgz

# glibc-solibs:
cd $PSOLIBS
mkdir -vpm755 etc/profile.d
cp -a $CWD/profile.d/* etc/profile.d
chown -R root:root etc
chmod 755 etc/profile.d/*
mkdir -vpm755 lib
cp -a $PKG/lib/* lib
( cd lib
  mkdir -vpm755 incoming
  mv *so* incoming
  mv incoming/libSegFault.so .
)
mkdir -vpm755 usr
cp -a $PKG/usr/bin usr
mv usr/bin/ldd .
rm usr/bin/*
mv ldd usr/bin
mkdir -vpm755 usr/lib
# The gconv directory has a lot of stuff, but including it here will save some problems.
# Seems standard elsewhere.
cp -a $PKG/usr/lib/gconv usr/lib
mkdir -vpm755 usr/libexec
cp -a $PKG/usr/libexec/pt_chown usr/libexec
cp -a $PKG/sbin .
mv sbin/ldconfig .
rm sbin/*
mv ldconfig sbin
mkdir -vpm755 install
install -vpm644 -oroot -groot $CWD/slack-desc.glibc-solibs install/slack-desc
install -vpm644 -oroot -groot $CWD/doinst.sh-glibc-solibs install/doinst.sh
#
# Ditch links:
find . -type l -exec rm {} \;
#
# Build the package:
makepkg -l y -c n $PKGSTORE/a/glibc-solibs-$VERSION-$PKGARCH-$BUILD.tgz

# And finally, the complete "all-in-one" glibc package is created
# from whatever was leftover:
cd $PGLIBC
mv $PKG/* .
mkdir -vpm755 etc/profile.d
cp -a $CWD/profile.d/* etc/profile.d
chown -R root:root etc
chmod 755 etc/profile.d/*
# Ditch links (these are in doinst.sh-glibc):
find . -type l -exec rm {} \;
mkdir -vpm755 install
install -vpm644 -oroot -groot $CWD/slack-desc.glibc install/slack-desc
install -vpm644 -oroot -groot $CWD/doinst.sh-glibc install/doinst.sh
( cd lib
  mkdir -vpm755 incoming
  mv *so* incoming
  mv incoming/libSegFault.so .
)
# Build the package:
makepkg -l y -c n $PKGSTORE/l/glibc-$VERSION-$PKGARCH-$BUILD.tgz

# Done!
