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

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")")

if [[ ! -f "$DIR/.needs_mount" ]]; then
    if ! mountpoint -q "$DIR"; then
        echo "Error: $DIR is not a SquashFS directory."
        exit 1
    fi
fi

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

echo "Disabling 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 image and restoring data..."

# Atomic copy-out
TEMP_DIR=$(mktemp -d /tmp/squash-dest.XXXXXXXX)
sudo rsync -aX "$DIR/" "$TEMP_DIR/" || { echo "Error: Failed to copy data."; exit 1; }

# Unmount
"$BIN_DIR/umount-squash-image" "$DIR"

# Restore original directory structure
OVERLAY_ROOT="$(dirname "$DIR")/.squashfs/$DIR_SHORT"
sudo rm -rf "$DIR"
sudo mv "$TEMP_DIR" "$DIR"

# Final cleanup
sudo rm -rf "$OVERLAY_ROOT" "${OVERLAY_ROOT}.img"

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