#!/bin/sh
#        file: /usr/bin/bootcdflopcp
#   copyright: Bernd Schumacher <bernd.schumacher@hpe.com> (2001-2020)
#     license: GNU General Public License, version 3
# description: bootcdflopcp - copy changes made after booting from bootcd to floppy

# do not use "set -e", because even a grep will fail, if all output is filtered
LANG=C

VERBOSE=""
FLOPPY=/dev/fd0

err()
{
  echo "ERROR: $1" >&2
  exit 1
}

while [ "$*" ]; do

  if [ "$1" = "-v" ]; then
    VERBOSE="-v"
    shift
  elif [ "$1" = "-d" ]; then
    FLOPPY=$2
    shift 2
  elif [ "$*" ]; then
    echo "Usage: bootcdflopcp [-v] [-d <device>]"
    echo "  use man bootcdflopcp to get help" >&2
    echo "  device can be another device instead of /dev/floppy" >&2
    exit 1
  fi

done

TMP=/tmp/flopcp$$
MNTP=/mnt/floppy

mkdir -p $MNTP || exit 1
mount $FLOPPY $MNTP || exit 1
trap "umount $MNTP; rmdir $MNTP; rm -f $TMP" 0

touch $MNTP/remove $MNTP/change $MNTP/ignore $MNTP/execute
chmod 755 $MNTP/execute

IGNORE=""
CHANGE=""
REMOVE=""

# Search all Files that differ
find /mnt/bootcd.upper/upper -type f| sed "s|/mnt/bootcd.upper/upper||" >$TMP

for f in `cat $TMP`; do
  if [ "`grep ^$f$ $MNTP/ignore`" ]; then
    IGNORE="$f $IGNORE"
    continue
  fi

  if [ -e "$f" ]; then
    if [ "`grep ^$f$ $MNTP/change`" ]; then
      CHANGE="$f $CHANGE"
      continue
    fi

    while :
    do
      echo -n "change $f (y/n) "
      read a
      # Next line handles EOF from a pipe as "n"
      [ $? -ne 0 ] && a="n"
      if [ "$a" = "y" ]; then
        echo $f >> $MNTP/change
        CHANGE="$f $CHANGE"
        break
      elif [ "$a" = "n" ]; then
        echo $f >> $MNTP/ignore
        IGNORE="$f $IGNORE"
        break
      fi
    done
  else
    if [ "`grep ^$f$ $MNTP/remove`" ]; then
      REMOVE="$f $REMOVE"
      continue
    fi
    while :
    do
      echo -n "remove $f (y/n) "
      read a
      # Next line handles EOF from a pipe as "n"
      [ $? -ne 0 ] && a="n"
      if [ "$a" = "y" ]; then
        echo $f >> $MNTP/remove
        REMOVE="$f $REMOVE"
        break
      elif [ "$a" = "n" ]; then
        echo $f >> $MNTP/ignore
        IGNORE="$f $IGNORE"
        break
      fi
    done
  fi
done

if [ "$VERBOSE" ]; then
  echo "Changing $CHANGE." >&2
  echo "Removing $REMOVE." >&2
  echo "Ignoring $IGNORE." >&2
fi

(cd /; tar cz -T $MNTP/change -f $MNTP/change.tgz)
exit 0
