#!/bin/bash
set -e

BASEDIR="/home/ls/gamestick"
IMG="$BASEDIR/original_image.img"
MOUNT_DIR="$BASEDIR/mounted"
SQUASH_DIR="$BASEDIR/squashfs/rootfs"
KERNEL_DIR="$BASEDIR/kernels"

# Создаем папки
mkdir -p "$MOUNT_DIR/p1" "$MOUNT_DIR/p7" "$MOUNT_DIR/p8"
mkdir -p "$SQUASH_DIR"
mkdir -p "$KERNEL_DIR"

echo "=== Attaching image ==="
LOOP_DEV=$(losetup --show -fP "$IMG")
if [ -z "$LOOP_DEV" ]; then
    echo "ERROR: Cannot attach loop device for $IMG"
    exit 1
fi
echo "Loop device: $LOOP_DEV"

echo "=== Creating partition mappings ==="
kpartx -av "$LOOP_DEV"

# Функция для монтирования с проверкой
mount_check() {
    local DEV="$1"
    local TARGET="$2"
    local TYPE="$3"

    echo "--- Mounting $DEV to $TARGET (${TYPE:-auto}) ---"
    if mount ${TYPE:+-t $TYPE} "$DEV" "$TARGET"; then
        echo "OK: Mounted $DEV"
    else
        echo "WARN: Failed to mount $DEV"
    fi
}

# Монтируем p1 (vfat)
mount_check "/dev/mapper/$(basename $LOOP_DEV)p1" "$MOUNT_DIR/p1" "vfat"

# Извлекаем ядро и содержимое p4
BOOT_PART="/dev/mapper/$(basename $LOOP_DEV)p4"
echo "--- Copying p4 to $KERNEL_DIR/p4.img ---"
sudo dd if="$BOOT_PART" of="$KERNEL_DIR/p4.img" bs=1M status=progress

echo "--- Extracting p4 contents with abootimg ---"
cd "$KERNEL_DIR"
if abootimg -x p4.img; then
    rm -f p4.img
    echo "OK: p4 contents extracted to $KERNEL_DIR (kernel, ramdisk, config)"
else
    echo "ERROR: Failed to extract p4.img with abootimg!"
    echo "The file $KERNEL_DIR/p4.img is kept for inspection."
fi

# Монтируем p5 (SquashFS / initramfs)
mount_check "/dev/mapper/$(basename $LOOP_DEV)p5" "$SQUASH_DIR" "squashfs"

# Монтируем p7/p8 (ext4)
mount_check "/dev/mapper/$(basename $LOOP_DEV)p7" "$MOUNT_DIR/p7" "ext4"
mount_check "/dev/mapper/$(basename $LOOP_DEV)p8" "$MOUNT_DIR/p8" "ext4"

echo
echo "=== MOUNT SUMMARY ==="
mount | grep "$BASEDIR" || echo "No mounts found in $BASEDIR"

echo "=== RESULT ==="
echo "Mounted FS : $MOUNT_DIR"
echo "Initramfs  : $SQUASH_DIR"
echo "Kernels    : $KERNEL_DIR"
echo "Loop dev   : $LOOP_DEV"

