#!/bin/bash
set -e

BASEDIR="/home/ls/gamestick"
MOUNT_DIR="$BASEDIR/mounted"
SQUASH_DIR="$BASEDIR/squashfs/rootfs"

echo "=== Unmounting mounted directories ==="
for DIR in "$SQUASH_DIR" "$MOUNT_DIR/p8" "$MOUNT_DIR/p7" "$MOUNT_DIR/p1"; do
    if mountpoint -q "$DIR"; then
        umount "$DIR" && echo "OK: Unmounted $DIR"
    else
        echo "INFO: $DIR was not mounted"
    fi
done

echo "=== Removing partition mappings and detaching loop devices ==="
LOOP_DEV=$(losetup -j "$BASEDIR/original_image.img" | cut -d':' -f1)
if [ -n "$LOOP_DEV" ]; then
    kpartx -d "$LOOP_DEV" && echo "OK: Removed partition mappings for $LOOP_DEV"
    losetup -d "$LOOP_DEV" && echo "OK: Detached loop device $LOOP_DEV"
else
    echo "INFO: No loop device found for $BASEDIR/original_image.img"
fi

echo "=== Done! ==="
