#!/bin/bash
# Lackadaisical squashfs tools - Destroy
BIN_DIR=$(dirname "$(readlink -f "$0")")
DIR="$1"

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

DIR=$(readlink -f "$DIR")
DIR_SHORT=$(basename "$DIR")

if [[ ! -f "$DIR/.needs_mount" ]]; then
  if ! mountpoint -q "$DIR"; then
    echo "Error: $DIR does not appear to be a SquashFS-backed directory (missing .needs_mount)."
    exit 1
  fi
fi

# Disable systemd service
ESC_PATH=$(systemd-escape -p "$DIR")
SERVICE_NAME="squash-mount@-$ESC_PATH"

echo "Disabling systemd service ($SERVICE_NAME)..."
sudo systemctl stop "$SERVICE_NAME" 2>/dev/null
sudo systemctl disable "$SERVICE_NAME" 2>/dev/null

# Ensure it is mounted to copy merged data
echo "Ensuring image is mounted to preserve data..."
"$BIN_DIR"/mount-squash-image "$DIR" 1>/dev/null 2>/dev/null

echo "Destroying SquashFS image and restoring data to normal directory..."

TEMP_DIR=$(mktemp -d)
# Copy data out (preserving all attributes)
sudo rsync -a "$DIR/" "$TEMP_DIR/"

# Unmount the overlay and squashfs
echo "Unmounting..."
"$BIN_DIR"/umount-squash-image "$DIR"

# Restore data to original location
echo "Restoring files..."
sudo rm -rf "$DIR"
sudo mv "$TEMP_DIR" "$DIR"

# Cleanup hidden image and overlay files
OVERLAY_ROOT=$(readlink -f "${DIR}/..")/.squashfs/${DIR_SHORT}
echo "Cleaning up ${OVERLAY_ROOT}..."
sudo rm -rf "${OVERLAY_ROOT}.img"
sudo rm -rf "${OVERLAY_ROOT}"

echo "Success: SquashFS image destroyed and data restored to $DIR."
exit 0

