#!/bin/bash

# Combine a root filesystem directory and a control image into an $ARCH-specific
# chroot containing native build control files, suitable for chrooting into.

if test $Argc -ne 2
{
  echo "usage: $0 "'$ARCH $CONTROL_IMAGE' >&2
  exit 1
}

# Make sure prerequisites exist

for i in build/{root-filesystem,native-compiler}-"$1" "$2"
{
  if test ! -e $i
  {
    echo "No $i" >&2
    exit 1
  }
}

if test $(id -u) -ne 0
{
  echo "Not root">&2
  exit 1
}

# Zap old stuff (if any)

test -z $CHROOT && setvar CHROOT = ""build/chroot-$1""
trap 'more/zapchroot.sh "$CHROOT"' EXIT
if test -e $CHROOT
{
  more/zapchroot.sh $CHROOT || exit 1
}

# Copy root filesystem and native compiler
cp -lan "build/root-filesystem-$1/." $CHROOT || exit 1
cp -lan "build/native-compiler-$1/." $CHROOT || exit 1

# splice in control image
if test -d $2
{
  mount -o bind $2 "$CHROOT/mnt" &&
  mount -o remount,ro "$CHROOT/mnt"|| exit 1
} else {
  mount -o loop $2 "$CHROOT/mnt" || exit 1
}'

# Output some usage hints

CPUS=1'" HOST=$1" chroot $CHROOT /sbin/init.sh