#!/bin/sh

reffile="$1"

if [ $# -ne 1  ]
then
  echo "usage: $0 referencefile" >&2
  exit 1
fi

if [ ! -f "${reffile}" ]
then
  echo "ERROR: reference file ${reffile} does not exist" >&2
  exit 1
fi
:

awk '/^d/ { print $NF } ' "${reffile}" | xargs echo mkdir -p

awk '

  # symlinks
  /^l/ {
    print "ln -s " $NF " " $(NF-2)
  }

  # regular files, file size > 0
  /^-/ && ($5 != "0" ) {

    if ($5 < 2147483648 ) {
      # files smaller 2 GB in one pass
      print "dd if=/dev/zero count=1 bs=" $5  " of=\"" $NF "\""
    } else {

      FILESIZE=$5
      MAXBLOCKSIZE=2147483647
      BLOCKCOUNT=int(FILESIZE/MAXBLOCKSIZE)
      REMAINING_BYTES=FILESIZE % MAXBLOCKSIZE

      print "dd if=/dev/zero bs=" MAXBLOCKSIZE " count=" BLOCKCOUNT " of=\"" $NF "\""
      if (REMAINING_BYTES != 0) {
        print "dd if=/dev/zero seek=" BLOCKCOUNT " obs=" MAXBLOCKSIZE " count=1 ibs=" REMAINING_BYTES " of=\"" $NF "\""
      }

    }
  }

  # regular empty files 
  /^-/ && ($5 == "0" ) {
    print "touch \"" $NF "\""
  }

  # permissions on directories and regular files
  /^[d-]/ {
    # print "chown " $3 ":" $4 " " $NF
    print "chmod u=" substr($1,2,3) ",g=" substr($1,5,3) ",o=" substr($1,8,3) " " $NF
  }

  ' "${reffile}"



