#!/bin/sh
#
# split-initramfs
#
# Splits large initramfs file for Parted Magic PXE in multiple smaller files,
# so Parted Magic PXE can be booted with tftp servers that can't transfer files
# larger than 32MB.
#
# Written by Gert Hulselmans, amended by Dick Burggraaff (burdi01)

# Split size in MB
SPLIT_SIZE=30

REAL_PATH="$(dirname "$(readlink -f "$0")")"

# This script is located either in .../boot/pxelinux/ (as distributed)
# or .../pmagic/ (when downloaded)
if [ "$(basename "$REAL_PATH")" = pxelinux ]; then
  REAL_PATH="$(dirname "$(dirname "$REAL_PATH")")/pmagic"
fi

if [ ! -e "$REAL_PATH/bzImage" -o ! -e "$REAL_PATH/initramfs" ]; then
  echo "Check if bzImage and initramfs exist in '$REAL_PATH/'."
  exit 1
fi

which_sub() {
  IFS_OLD=$IFS ; IFS=':'
  for i in $PATH; do
    if [ -x "$i/$1" ] ; then
      IFS=$IFS_OLD ; return 0
    fi
  done
  IFS=$IFS_OLD ; return 1
}

for PROGRAM in readlink dirname head tr mkdir gzip find split rm cut; do
  if ! which_sub $PROGRAM ; then
    echo "The '$PROGRAM' program could not be found."
    echo "Install it and try again."
    exit 1
  fi
done

cd "$REAL_PATH"
rm -f initbase pmagic-*.sqfs?? pmagic-*.sqfs#*

echo "Extracting initramfs ..."
TEMP_PMAGIC_DIR="/tmp/pmagic-initramfs-`head -c 1000 /dev/urandom | tr -dc a-zA-Z0-9 | head -c 8`"
mkdir -p "$TEMP_PMAGIC_DIR"
cd "$TEMP_PMAGIC_DIR"
# Not all gzip implementations handle this gracefully
#gzip -cd "$REAL_PATH/initramfs" | cpio -im
gzip -d < "$REAL_PATH/initramfs" | cpio -im

echo "Building and compressing initbase ..."
[ $(id -u) = 0 ] && OWNER=  || OWNER="--owner root:root"
find ./ ! -name pmagic-*.sqfs | cpio --quiet -H newc $OWNER -o | gzip -9 > "$REAL_PATH/initbase"

FILE=$(ls pmagic-*.sqfs)
echo "Splitting '$FILE' into multiple files ..."
# Newer versions of 'split' seem to not accept a suffix length = 2
#split -a 2 -b ${SPLIT_SIZE}m -d --verbose ${FILE} ${FILE}
split -b ${SPLIT_SIZE}m -d --verbose $FILE $FILE#

INITRD='pmagic/initbase'
echo "Creating '${FILE}NN.cgz ..."
for PPART in $FILE#* ; do
  # Not all shells support substrings
  #PART=$FILE${PPART: -2}     # Note the space between ":" and "-" !!!
  PART=$FILE${PPART#${PPART%??}}
  echo $PART.cgz
  mv $PPART $PART
  echo $PART | cpio --quiet -H newc -o | gzip -9 > "$REAL_PATH/$PART.cgz"
  INITRD="$INITRD,pmagic/$PART.cgz"
done

echo Removing temporary files ...
rm -rf "$TEMP_PMAGIC_DIR"

echo "DEFAULT pmagic

LABEL pmagic
LINUX pmagic/bzImage
INITRD $INITRD
APPEND edd=off load_ramdisk=1 prompt_ramdisk=0 rw vga=normal loglevel=9 max_loop=256
" > "$REAL_PATH/stanza.txt"

echo "
Copy the following files to your PXE server:
-- $REAL_PATH/bzImage
-- $REAL_PATH/initbase
-- $REAL_PATH/$FILE??.cgz
and use
-- $REAL_PATH/stanza.txt
as the basis for your PXE configuration.
"


