#!/bin/sh
# Check for some common errors after building chapter 5 packages.
# To build LFS, /bin/sh needs to be bash.  This script actually uses
# bashisms instead of portable sh, but for its intended use that is
# fine.

# First check that /bin/sh is not dash
# (treated as a fatal error because people see weird and wonderful
# errors if they use dash, and should start over.)
/bin/sh --version  >/dev/null
if [ $? -ne 0 ]; then
  echo "ERROR: read the Host System Requirements for /bin/sh"
  exit 1
fi

# Warn if user is root - allow it in case user went into chroot
# and had to come back
test $UID = 0 &&
echo "WARNING: you should not be root when building chapter 5"

# Ensure that tools is at the front of the path for this script.
# Without this, several glibc libs, and libstdc++, *appear* to be
# linked to the host.
FIRSTDIR=$(echo $PATH | cut -d ':' -f 1)
if [ "$FIRSTDIR" != "/tools/bin" ]; then
	echo "PATH did not begin with /tools/bin"
	PATH=/tools/bin:$PATH
fi

# NOTE: Do NOT run this before glibc has been built, otherwise
# the library tests will fail when gcc pass 1 has been installed.
# (libcc1.so links to the host)

# Check the programs, except any -lfs- progs from pass 1
PROGS=$(ls /tools/bin/* | sed -e 's/.*-lfs-.*//' -e '/^$/d' )
TOOLS_HOSTPROGS=n

for P in $PROGS ; do
  ldd $P | grep -q ' /lib'  && echo "$P is linked to /lib" &&
  TOOLS_HOSTPROGS=y
  ldd $P | grep -q ' /usr/lib'  && echo "$P is linked to /usr/lib" &&
  TOOLS_HOSTPROGS=y
done

TOOLS_HOSTLIBS=0
# ldd warns about lack of execute perm, so send that to /dev/null
LIBS=$( ls /tools/lib/lib*.so)
# what happens if anybody tries to build on i586 ?
if ! [ -f /tools/bin/x86_64-unknown-linux-gnu-gcc ] &&
   ! [ -f /tools/bin/i686-pc-linux-gnu-gcc ]; then
fi
if !  [ -z "$LIBS" ]; then
  for L in "$LIBS" ; do
    ldd $L 2>/dev/null | grep -q ' /lib' &&
    echo "$L is linked to /lib" && TOOLS_HOSTLIBS=y
    ldd $L 2>/dev/null | grep -q ' /usr/lib' &&
    echo "$L is linked to /usr/lib" && TOOLS_HOSTLIBS=y
  done
else
  echo "no libs to test"		
fi

if [ $TOOLS_HOSTPROGS = "y" ] || [ $TOOLS_HOSTLIBS = "y" ]; then
  echo 'ERROR'
  exit 1
fi

