#!/bin/sh
# /usr/share/bootcd/bootcdstart
# will be called by /etc/init.d/bootcd or /lib/systemd/system/bootcd.service
# both will source /etc/default/bootcd

[ "$MNT" ] || MNT=/mnt
[ "$FSTYPES" ] || FSTYPES="ext3,ext2,reiserfs,iso9660,vfat,auto"
[ "$BOOT_ONLY_WITH_FLOPPY" ] || BOOT_ONLY_WITH_FLOPPY="no"

if [ ! "$FLOPPY" ]; then
  # Some machines do not support a FLOPPY. In this case a disk with floppy size is searched.
  # If a disk with size 1440 is found we assume it should be used as floppy
  if [ "$(echo " aarch64 " | grep " $(uname -m) ")" ]; then
    FLOPPY="$(cat /proc/partitions | sed -E -n -e "s|\s*\S+\s+\S+\s+1440\s+(\S+)$|/dev/\1|p")"
  else
    FLOPPY=/dev/fd0
  fi
fi

my_exit()
{
  echo "bootcd: $2"
  if [ "$BOOT_ONLY_WITH_FLOPPY" = "yes" -a $1 != 0 ]; then
    echo "The floppy could not be mounted."
    echo "Manual interaction required."
    # Start a single user shell on the console
    /sbin/sulogin $CONSOLE
  fi
  exit 0
}

startscript()
{
  # bootcdwrite modifies this script. FLOPPY could be unset.
  if [ ! "$FLOPPY" ]; then
    my_exit 0 "No Floppy device specified !!"
  fi

  # Only run this script if we have booted from bootcd
  if [ ! "$(grep "\<bootcd=" /proc/cmdline)" ]; then
    my_exit 0 "not booted from bootcd"
  fi

  # Try only once, if /dev/fd0 is readable.
  cat $FLOPPY >/dev/null
  RET=$?
  [ $RET -eq 0 ] || my_exit $RET "$FLOPPY not readable"

  echo "Reading floppy"
  fsck -a -t $FSTYPES $FLOPPY
  mount -v -o ro -n -t $FSTYPES $FLOPPY $MNT
  RET=$?
  [ $RET -eq 0 ] || my_exit $RET "$FLOPPY not mountable"

  [ -f $MNT/change.tgz ] && (cd /; tar xzf $MNT/change.tgz)

  [ -f $MNT/remove ] && for i in `cat $MNT/remove`
  do
    rm -f /$i
  done

  [ -x $MNT/execute ] && $MNT/execute
  umount $MNT
}

startscript
