#! /bin/bash

#
# remaster openSUSE CD & modify boot catalog position
#


function m_cd {
  SOURCE=$1
  DEST=$2
  FILL=$3

  [ -d "$SOURCE" -a -n "$DEST" ] || {
    echo "usage: mk_cd [ -c boot_catalog_sector ] dir iso_file"
    exit 1
  }

  SORTFILE=`mktemp /var/tmp/mk_cd-XXXXXX`

  if [ -d $SOURCE/boot/i386 ] ; then
    BOOT_BASE_DIR=boot/i386
    BOOT_ISOLINUX=boot/i386/loader
    # for sorting
    ALT_BOOT_ISOLINUX=boot/x86_64/loader
  elif [ -d $SOURCE/boot/x86_64 ] ; then
    BOOT_BASE_DIR=boot/x86_64
    BOOT_ISOLINUX=boot/x86_64/loader
    # for sorting
    ALT_BOOT_ISOLINUX=boot/i386/loader
  fi

  [ -z "$BOOT_BASE_DIR" ] && {
    echo "not bootable: $SOURCE"
    exit 1
  }

  [ ! -w "$SOURCE/$BOOT_BASE_DIR" ] && {
    echo "must be writable: $BOOT_BASE_DIR"
    exit 1
  }

  [ ! -w "$SOURCE/$BOOT_ISOLINUX/isolinux.bin" ] && {
    echo "must be writable: $BOOT_ISOLINUX/isolinux.bin"
    exit 1
  }

  if [ -n "$FILL" ] ; then
    dd if=/dev/zero of=$SOURCE/$BOOT_BASE_DIR/fill bs=2k count=$FILL 2>/dev/null
  fi

  echo "$SOURCE/$BOOT_BASE_DIR/fill 5" >>$SORTFILE
  echo "$SOURCE/$BOOT_BASE_DIR/boot.catalog 4" >>$SORTFILE
  find $SOURCE/$BOOT_ISOLINUX -printf "%p 2\n" >>$SORTFILE
  # last priority wins
  echo "$SOURCE/$BOOT_ISOLINUX/isolinux.bin 3" >>$SORTFILE
  if [ -d "$SOURCE/$ALT_BOOT_ISOLINUX" ] ; then
    find $SOURCE/$ALT_BOOT_ISOLINUX -printf "%p 1\n" >>$SORTFILE
  fi

  PARAMS="-r -J -l -pad -input-charset utf-8 -sort $SORTFILE -no-emul-boot -boot-load-size 4 -boot-info-table \
          -b $BOOT_ISOLINUX/isolinux.bin -c $BOOT_BASE_DIR/boot.catalog \
          -hide $BOOT_BASE_DIR/boot.catalog -hide-joliet $BOOT_BASE_DIR/boot.catalog \
          -hide $SOURCE/$BOOT_BASE_DIR/fill -hide-joliet $SOURCE/$BOOT_BASE_DIR/fill"

  mkisofs -p "KIWI - http://kiwi.berlios.de" -publisher "SUSE Linux Products GMBH" $PARAMS -sysid Win32 -A "GNOME 3 Live DVD" -o $DEST $SOURCE

  [ -e "$SORTFILE" ] && rm $SORTFILE
  [ -e $SOURCE/$BOOT_BASE_DIR/fill ] && rm $SOURCE/$BOOT_BASE_DIR/fill

  boot_catalog=`isoinfo -d -i $DEST | perl -ne 'print $1 if /boot catalog is in sector (\d+)/'`
  boot_loader=`isoinfo -d -i $DEST | perl -ne 'print $1 if /Bootoff \S+ (\d+)/'`
}

function show_info {
  ls -l $1
  echo "boot catalog is at sector $boot_catalog"
  echo "boot loader starts at sector $boot_loader"
}

while getopts c: opt ; do
  case $opt in
    c) catalog=$OPTARG
      ;;
  esac
done
shift $(($OPTIND - 1))

m_cd $1 $2 || exit 1

[ -z "$catalog" ] && catalog=$boot_catalog

if [ "$boot_catalog" -eq "$catalog" ] ; then
  show_info $2
  exit 0
fi

if [ "$boot_catalog" -gt "$catalog" ] ; then
  show_info $2
  echo "can't move boot catalog to sector $catalog"
  exit 2
fi

m_cd $1 $2 $(($catalog-$boot_catalog)) || exit 1
show_info $2