#!/bin/csh

if ( "" == "$2" ) then
  echo "Usage: genramdisk <image file> <package> [package ...]"
  echo 'Environment variables:'
  echo '$APTCONFDIR - apt configuration to copy (default: /etc/apt)'
  echo '$RAMDISK_SIZE - RAM disk size in Mb (default: calculate automatically)'
  exit 1
endif

set image="$1"
shift

if ( -s "$image" ) then
  echo "File $image already exists, refusing to overwrite"
  exit 1
endif

umask 022
set world=`mktemp -d "$TMP/world-XXXXXXXX-root"`
set target=`mktemp -d "$TMP/ramdisk-XXXXXXXX-root"`

# installworld and postinstall may leave dirty filesystem image;
# to improve compression effectiveness, use temporary directory
# for intermediate storage
# it also makes possible the automatic calculation of disk space
echo "Installing the packages into $world ..."
installworld "$world" $*
postinstall "$world"

set fs_size=""

if ( $?RAMDISK_SIZE ) then
# $RAMDISK_SIZE must contain FS size in megabytes
  set fs_size=`echo "$RAMDISK_SIZE" | sed -re '/^[^0-9]$/d;s/^[^0-9]+//g;s/[^0-9].*//g'`
endif

if ( "" == "$fs_size") then
# calculate FS size automatically
  set world_size=`du -sBM $world | sed -re 's,[^0-9].*,,g'`
  @ fs_size = "$world_size" * 11 / 10 + 100
endif

echo "Creating $fs_size Mb image file $image ..."
# block size should be 4 kb
@ num_blocks = "$fs_size" * 256
touch "$image"
mke2fs -j -m0 -b 4096 -F "$image" "$num_blocks" \
&& mount "$image" "$target" -o loop || exit 1

rsync -PHax "$world/" "$target/"
rm -rf "$world"

umount -d "$image" && rmdir "$target"
echo "Compressing $fs_size Mb image..."
pv -rb < "$image" | xz -C crc32 -c9 > "${image}.xz"
test -s "${image}.xz" && rm -f "$image"
echo "${image}.xz ready"
