#!/bin/bash
# Lackadaisical squashfs tools - Mount

DIR="$1"
if [[ -z "$DIR" ]]; then
  echo "Usage: $0 <directory>"
  exit 1
fi

DIR=$(readlink -f "$DIR")
DIR_SHORT=$(basename "$DIR")
BIN_DIR=$(dirname "$(readlink -f "$0")")

OVERLAY_ROOT="$(dirname "$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

# Unmount existing first
"$BIN_DIR/umount-squash-image" "$DIR" 2>/dev/null

# Mount lower squashfs image via loopback
mkdir -p "$OVERLAY_LOWER"
sudo mount "${OVERLAY_ROOT}.img" "$OVERLAY_LOWER" -t squashfs -o loop
if [[ $? -ne 0 ]]; then
    echo "Error: Failed to mount squashfs image." >&2
    exit 1
fi

# Mount overlay
sudo mount -t overlay none "$OVERLAY_TARG" \
    -o lowerdir="$OVERLAY_LOWER",upperdir="$OVERLAY_UPPER",workdir="$OVERLAY_WORK"

if [[ $? -ne 0 ]]; then
    echo "Error: Failed to mount overlay." >&2
    sudo umount "$OVERLAY_LOWER" 2>/dev/null
    exit 1
fi

echo "SquashFS filesystem is mounted and ready."
