#!/bin/bash
DIR="$@"
DIR=$(readlink -f "$DIR")
DIR_SHORT=$(basename "$DIR")
BIN_DIR=$(dirname "$(readlink -f "$0")")
mkdir -p "$DIR"

OVERLAY_ROOT=$(readlink -f "${DIR}/..")/.squashfs/${DIR_SHORT}
OVERLAY_UPPER=${OVERLAY_ROOT}/upper
OVERLAY_LOWER=${OVERLAY_ROOT}/lower
OVERLAY_WORK=${OVERLAY_ROOT}/work
OVERLAY_TARG=$DIR

if [ ! -f "${OVERLAY_ROOT}.img" ]; then
    echo "Error: SquashFS image ${OVERLAY_ROOT}.img not found." >&2
    exit 1
fi

"$BIN_DIR"/umount-squash-image "$@" 1>/dev/null 2>/dev/null

sudo mount "${OVERLAY_ROOT}.img" "$OVERLAY_LOWER" -t squashfs -o loop
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
    echo "Error: Failed to mount squashfs image (exit code $EXIT_CODE)." >&2
    exit $EXIT_CODE
fi

sudo mount -t overlay -o lowerdir="$OVERLAY_LOWER",upperdir="$OVERLAY_UPPER",workdir="$OVERLAY_WORK" none "$OVERLAY_TARG"
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
    echo "Error: Failed to mount overlay (exit code $EXIT_CODE)." >&2
    # Cleanup: unmount the lower squashfs if overlay mount fails
    sudo umount "$OVERLAY_LOWER" 2>/dev/null
    exit $EXIT_CODE
fi

echo "SquashFS filesystem is mounted and ready."
exit 0
