#!/bin/bash
set -e
if [ X${SOURCED} = X ]; then
  echo "Please copy, configure and source config/sourceme.cfg.example then run me"
  exit 1
fi

if [ X${1} = X ]; then
  echo "Usage: $0 dirname"
  exit 0
fi

CWD="`pwd`"
cd "`dirname $0`/.."
LTPTOP="`pwd`"
BUILDTOP="${LTPTOP}//${1}"

if [ ! -d "${LTP_SRCDIR}" ]; then
  echo "LTP_SRCDIR not defined, using ${LTPTOP}/src"
  LTP_SRCDIR="${LTPTOP}/src"
fi

if [ ! -f "${LTP_SRCDIR}/ltp-current.tar.bz2" ]; then
  echo "LTP archive does not exist!"
  echo "Create a symlink (ltp-current.tar.gz) to the current LTP tarball."
  exit 1
fi

if [ -d "${BUILDTOP}" ]; then
  echo "Removing old $1 directory"
  rm -rf "${BUILDTOP}"
fi

mkdir -p "${BUILDTOP}"
cd "${BUILDTOP}"

echo "Installing sources..."
bzip2 -dc ${LTP_SRCDIR}/ltp-current.tar.bz2 | tar xf -
cd ltp*
TOP_SRCDIR="`pwd`"

# apply LTP patches for UCLINUX build
echo "Patching TLP..."
patch -p0 < ${LTP_SRCDIR}/ltp.patch

echo "Building autotools (This requires automake 2.61 or higher)"
make autotools

echo "Copying/creating support files..."
echo "echo 'Using in-tree sourceme.cfg'" > sourceme.cfg
set | egrep -e PFX=\|CFLAGS=\|LDFLAGS=\|AR=\|AS=\|CPP=\|CC=\|LD=\|NM=\|OBJCOPY=\|OBJDUMP=\|RANLIB=\|STRIP=\|UCLINUX=\|SOURCED\|LTP_SRCDIR\|FMT\|GCC\|INSTPFX\|DASHJ\|BE >> sourceme.cfg
echo "export PFX CFLAGS LDFLAGS AR AS CPP CC LD NM OBJCOPY OBJDUMP RANLIB STRIP UCLINUX SOURCED LTP_SRCDIR FMT GCC INSTPFX DASHJ BE" >> sourceme.cfg

echo -e "source sourceme.cfg\\n${TOP_SRCDIR}/configure --host=i686-redhat-linux" > configure.cmd
echo -e "source sourceme.cfg\\nmake \$DASHJ" > make.cmd
cat > install.cmd << EOF
set -e
source sourceme.cfg
${LTPTOP}/bin/fsmk /tmp/out.iso
for i in \$INSTPFX;
  do make DESTDIR=\${i} SKIP_IDCHECK=1 install
  mkdir -p \${i}/bin
  cp sandbox/sandbox \${i}/bin/sandbox
  cp \$LTP_SRCDIR/setup-ltp* \${i}/bin
  cp \$LTP_SRCDIR/fs* \${i}/bin
  cp /tmp/out.iso \${i}/mnt
done
rm -f /tmp/out.iso
EOF
chmod 755 *cmd

if [ "X${GCC}" = X ]; then
  echo "Performing pre-build steps for TI compiler tools..."
  cp ${LTPTOP}/bin/prebuild .
  ./prebuild
fi

echo "Creating Makefile.defs"
cat << EOF > Makefile.defs
CC=${CC}
AR=${AR}
CFLAGS=${CFLAGS}
LDFLAGS=${LDFLAGS}
EOF

if [ -f "${LTP_SRCDIR}/sandbox-src.tar.bz2" ]; then
  echo "Creating sandbox"
  bzip2 -dc "${LTP_SRCDIR}/sandbox-src.tar.bz2" | tar xf -
  pushd sandbox
  make
  chmod 755 sandbox
  popd
fi

if [ ! -x ${LTPTOP}/bin/testdriver ]; then
  echo "Creating testdriver"
  bzip2 -dc "${LTP_SRCDIR}/testdriver-src.tar.bz2" | tar xf -
  pushd testdriver
  make
  chmod 755 testdriver
  cp testdriver ${LTPTOP}/bin/testdriver
  popd
fi


echo "${TOP_SRCDIR} is ready.  Please configure, make and install using these files:"
ls -F *cmd
