#!/bin/sh

# This script is run by the UML instance to set up the UML environment and
# pass control on to mktools-build.sh.  If you don't need User Mode Linux
# (I.E. you're running as root on a new enough kerenel), you can skip this
# script and run mktools-build.sh directly.

# Although we're running as root in the UML instance, UML shouldn't be running
# as root on the host system.  As a result, large chunks of our hostfs are
# effectively read only.  We can't write to the root directory, and we can't
# mknod or chown anywhere.  Also, the mounted synthetic filesystems (/proc
# and /dev/pts) refer to the parent kernel, not the one running our processes.

# To get around this we create a loopback mounted ext2 image, bind mount all
# the other directories from the real root dir into it (and duplicate all the
# symlinks, so we can rebuild under ourselves), mount the UML instance's proc
# and devpts into it, and chroot.

# This assumes we have a sane host system, where /home, /proc, and /dev/pts
# exist, and where /mktools.sh and /tools do not already exist.  Then again,
# we're assuming you've got a sane enough host system to compile the rest of
# the tools directory anyway.  (If you haven't, just grab a prepackaged tools
# and use that.)

# Note that sane is not the same thing as well-constructed.  For example,
# we use mount -n in case somebody is crazy enough to run this as root on an
# old system where /etc/mtab is not a symlink to /proc/mounts.


# First, replace /dev with a ramfs containing the dev entries we need.  (The
# permissions on things like /dev/console and /dev/loop0 are often wrong for
# us.)

mount -n -t ramfs /dev /dev &&
mknod -m 700 /dev/console c 5 1 &&
mknod -m 700 /dev/zero c 1 5 &&
mknod -m 700 /dev/loop0 b 7 0 &&
mkdir /dev/pts

function remount()
{
  echo "Creating ext2 image..." &&

  mount -n -t proc /proc /proc &&
  export PATH=/sbin:/usr/sbin:/bin:/usr/bin &&
  cd "$DIR/tmpdir" &&
  dd if=/dev/zero of=tools.img bs=8192 count=65536 &&
  mke2fs -F tools.img &&
  echo "Remounting parent system for chroot environment..." &&
  mkdir sub &&
  losetup /dev/loop0 tools.img &&
  mount -n -t ext2 /dev/loop0 sub &&
  cd sub &&
  for i in /*
  do
    i="${i:1}"
    if [ "$i" != "lost+found" ]
    then
      if [ -h "$i" ]
      then
        ln -s $(ls -l "$i" | sed 's/^.*-> //') "$i"
      elif [ -d "/$i" ]
      then
        mkdir "$i"
        mount -n -o bind "/$i" "$i"
      fi
    fi
  done
  if [ $? -ne 0 ]; then exit 1; fi
  mount -n -t devpts /dev/pts dev/pts &&
  # Now chroot and hand control off to next script
  chroot . /usr/bin/env PATH=/usr/bin:/bin:/usr/sbin:/sbin HOME=/root TERM=linux /bin/sh -c "cd $DIR;exec ./mktools-build.sh" &&
  # Create the tarball we went through this whole exercise to get.
  tar cvjf ../tools.tar.bz2 tools
  sync
  halt -f
}

remount </dev/console >/dev/console 2>/dev/console
