#!/bin/bash

# Copyright 2006 Rob Landley <rob@landley.net> and TimeSys Corporation.
# Licensed under GPL version 2

if [ $# -ne 3 ]
then
  echo "usage: $(basename $0) <directory> <original> <output>"
  exit 1
fi

BLOCK_SIZE=512

if [ ! -f "$2" ]; then
  echo "second argument must be a file"
  exit 1
fi

if [ ! -d "$1" ]; then
  echo "First argument must be a directory"
  exit 1
fi

INPUT_SIZE=$(stat -c "%s" $2)
GZIP_START=$(grep -aboP "\x1f\x8b\x08" $2|cut -d":" -f1)

echo "creating new image file from $2"
dd if=/dev/zero of=$3 bs=$BLOCK_SIZE count=$(($INPUT_SIZE/BLOCK_SIZE))
dd if=$2 of=$3 bs=$BLOCK_SIZE count=$(($GZIP_START/BLOCK_SIZE)) conv=notrunc
echo "dumping new initrd from $1 into $2"
CDIR=$(pwd)
cd "$1";find . | cpio -o -H newc | gzip -c -9 | dd  of=$CDIR/$3 bs=1 seek=$GZIP_START conv=notrunc
