#!/bin/sh
#

LTPBIN=/tmp/ltp

echo "Removing old ${LTPBIN}"
rm -rf ${LTPBIN}
mkdir -p ${LTPBIN}
cp /opt/ltp/testcases/bin/test1 /opt/ltp/testcases/bin/test3 /opt/ltp/testcases/bin/tst_resm ${LTPBIN}
echo "11112222" > ${LTPBIN}/spliceme
# for getdtablesize01
touch /etc/hosts

cd /
chmod 1777 /tmp
PATH=${LTPBIN}:$PATH
export PATH

if [ X${1} = X ]; then
  set -v
  rm -f /mnt/smallblock.file
  umount /mnt/smallblock || true
  mkdir -p /mnt/smallblock
  echo "Creating file for block device to ensure loop0 is live"
  dd if=/dev/zero of=/mnt/smallblock.file bs=1024 seek=1000 count=1
  mkfs.ext2 -F /mnt/smallblock.file
  mount -o loop /mnt/smallblock.file /mnt/smallblock || exit 1
  cd ${LTPBIN}

else
  FSTYPE=${1}
  mkdir -p /chroot
  echo "Unmounting /chroot volumes"
  for i in /proc /dev/pts /sys /tmp ""; do
    umount /chroot${i} || true
  done
      
  case ${FSTYPE} in
    cifs)
      depmod -a
      modprobe cifs
      echo "Mounting CIFS volume: $*"
      mount -t cifs $2 -o $3 /chroot || exit 1
    ;;
    ext2)
      echo "Creating file for block device"
      dd if=/dev/zero of=/mnt/${1} bs=1024 seek=${2} count=1
      mkfs.ext2 -F /mnt/${1}
    
      echo "Remounting /chroot"
      mount -o loop /mnt/$1 /chroot || exit 1
    ;;
    *)
      echo "Unknown fstype. Exiting"
      exit 1
    ;;
  esac

  echo "Removing old files"
  rm -rf /chroot
  echo "Copying filesystem to /chroot"
  cp -a bin dev home initrd sbin usr boot etc init lib opt root tmp var /chroot
  mkdir /chroot/mnt

  rm /chroot/etc/mtab
  grep rootfs /etc/mtab > /chroot/etc/mtab
  echo "Changing root"
  chroot /chroot /bin/setup-ltp-chroot ${LTPBIN}
fi
