#!/bin/sh

set -e

# Make local mount points
mkdir -p mnt1 mnt2
# Mount bootdisk image read-only
mount boot.img mnt1 -o loop,ro -t msdos
# Get the initial ramdisk it contains
cp mnt1/initrd.img .
# Finished with boot image for now.
umount mnt1
# Unzip and mount it
mv initrd.img initrd.gz
gunzip initrd.gz
# Prevent warning about having to check the filesystem
tune2fs -c 0 -i 0 initrd >/dev/null
mount initrd mnt2 -o loop

# Work in initial ramdisk
# Rename it's init
mv mnt2/sbin/init mnt2/sbin/init_real
# Put BRLTTY on it
cp brltty mnt2/sbin
# New init is a link to BRLTTY
ln -s brltty mnt2/sbin/init
# Help files and tables (if the person isn't familiar...)
if [ -d etcbrltty ]; then
  mkdir -p mnt2/etc/brltty
  install etcbrltty/* mnt2/etc/brltty
fi
# Make sure some needed device files are present
# ttyS0 ttyS1 tty0
for i in ttyS0 ttyS1 tty0; do
  if [ ! -e mnt2/dev/$i ]; then
    cp -a /dev/$i mnt2/dev/$i
    chown root:root mnt2/dev/$i
  fi
done
# vcsa or vcsa0
# NB this doesn't handle devfs...
if [ ! -e mnt2/dev/vcsa -a ! -e mnt2/dev/vcsa0 ]; then
  for i in vcsa vcsa0; do
    if [ -c /dev/$i ]; then
      if [ -h /dev/$i ]; then
        tgt="`readlink /dev/$i`"
        # This assumes the link is relative...
        if [ -c /dev/$tgt ]; then
          cp -a /dev/$tgt mnt2/dev
        else
          echo "Failed to get link target of /dev/$i"
          echo "Failed!!"
          exit 1
        fi
      fi
      cp -a /dev/$i mnt2/dev
    fi
  done
fi
if [ ! -e mnt2/dev/vcsa -a ! -e mnt2/dev/vcsa0 ]; then
  echo "Failed to create mnt2/dev/vcsa"
  echo "Failed!"
  exit 1
fi

# Done with initial ramdisk. wrap it up.
umount mnt2
gzip -9 initrd
mv initrd.gz myroot.img
