#!/bin/sh

THIS_DIR=$(realpath $(dirname "$0"))

if [ "$1" = '-q' ] ; then
    QUIET=$1
    shift 1
else
    QUIET=
fi

PKGDIR=$1
E2ACCESS_DIR=$2
TARGET=$3

if [ ! -e "$PKGDIR" ] || [ ! -e "$E2ACCESS_DIR" ] || [ ! "$TARGET" ] ; then
    echo "Usage: $0 [ -q ] <package directory> <e2access directory> <target>" 1>&2
    exit 1
fi

PKGDIR=`realpath "$PKGDIR"`
E2ACCESS_DIR=`realpath "$E2ACCESS_DIR"`
TARGET=`realpath "$TARGET"`

# Initialise the program details and environment.

E2ACCESS="$E2ACCESS_DIR"/e2access
export LD_LIBRARY_PATH="$E2ACCESS_DIR"

# Make a filesystem for the example.

mkdir tmp_e2test
cd tmp_e2test
mkdir -p home/paulb/many
cd home/paulb/many

# Populate the directory with plenty of files.

for N in `seq 1 400`; do
    echo "Contents of #$N." > "file-$N".txt
done

cd ..

# Put a file in the directory above.

cp "$PKGDIR/../docs/LICENCE.txt" .

# Leave the filesystem root.

cd ../..

# Create a filesystem image.

EXTRA=2000
SIZE=$(du -s -k home | cut -f 1)
TOTAL=$(($SIZE + $EXTRA))

dd if=/dev/zero of="$TARGET" bs=1024 count=$TOTAL

if ! $(/sbin/mkfs.ext2 -q "$TARGET") ; then
    exit 1
fi

# Add the directory and files to the image.

"$E2ACCESS" "$TARGET" --make-dirs home/paulb/many

"$E2ACCESS" "$TARGET" --copy-in $(find home/paulb/many -maxdepth 1 -type f | sort) home/paulb/many
"$E2ACCESS" "$TARGET" --copy-in $(find home/paulb -maxdepth 1 -type f | sort) home/paulb

# Leave the root of the filesystem.

cd ..

if [ ! "$QUIET" ] ; then
    "$E2ACCESS" "$TARGET" --list-dirs ''
    "$E2ACCESS" "$TARGET" --list-dirs 'home'
    "$E2ACCESS" "$TARGET" --list-dirs 'home/paulb'
    "$E2ACCESS" "$TARGET" --list-dirs 'home/paulb/many'
fi

rm -r tmp_e2test
