#!/bin/sh

set -e

ISO_IMG='/tmp/t e s t.iso'
MNT_PNT='/tmp/t e s t_iso'

echo '~~~ Create an iso image from the source tree'
# Add a symlink to test fix of https://bugs.debian.org/1083039
ln -snf debian/rules symlink_to_rules
xorriso -outdev "$ISO_IMG" -charset ascii \
	-map . / \
	-chown_r 0 / -- \
	-chgrp_r 0 / -- \
	-compliance always_gmt_off \
	2>&1

echo '~~~ Mount the iso image'
fuseiso -p "$ISO_IMG" "$MNT_PNT"

echo '~~~ Showcase the content of the iso image'
tree -DFugs "$MNT_PNT"

echo '~~~ Check the iso image against the source tree'
# Compare output of 'tree' calls ignoring directories,
# their sizes differs no matter what
tree -DFs . | grep -v '/$' >/tmp/source_tree.tree
cd "$MNT_PNT"
tree -DFs . | grep -v '/$' >/tmp/mounted_iso.tree
cd "$OLDPWD"
diff /tmp/source_tree.tree /tmp/mounted_iso.tree
# Compare files as to content
find . -type f -exec cmp {} "$MNT_PNT"/{} \;

echo '~~~ Compare "stat *" results of fuseiso mount against what is expected'
stat --printf='%s %b %B %n\n' "$MNT_PNT"/* >/tmp/stat-MNT_PNT.out
diff debian/tests/stat-MNT_PNT.expected /tmp/stat-MNT_PNT.out

fusermount -u "$MNT_PNT"

echo '~~~ Check mounting with fuse options after the positional parameters'
fuseiso -p "$ISO_IMG" "$MNT_PNT" -o uid=$(id -u),gid=$(id -g)
ls -ld "$MNT_PNT"
fusermount -u "$MNT_PNT"

echo '~~~ Check mounting with fuse options ahead of the positional parameters'
fuseiso -o uid=$(id -u),gid=$(id -g) -p "$ISO_IMG" "$MNT_PNT"
ls -ld "$MNT_PNT"
fusermount -u "$MNT_PNT"

echo '~~~ Check mounting single-threaded with fuse options in mixed positions'
fuseiso -o uid=$(id -u) -s -p "$ISO_IMG" "$MNT_PNT" -o gid=$(id -g)
ls -ld "$MNT_PNT"
fusermount -u "$MNT_PNT"

echo '~~~ Check mounting in debug mode'
fuseiso -dp "$ISO_IMG" "$MNT_PNT" >debug.out 2>&1 &
sleep 1
ls -ld "$MNT_PNT"
fusermount -u "$MNT_PNT"
cat debug.out
grep -E '^Data Preparer Identifier +: XORRISO' debug.out

echo '~~~ Call the alternative binary name with option -V'
fuseiso9660 -V | tee version.out
grep -i fuse version.out >/dev/null

echo '~~~ Remove the iso image'
rm "$ISO_IMG"
