#!/bin/bash

# =============================
# Script to Extract Files from usbboot.img
# =============================

# Configuration
IMAGE_FILE="usbboot.img"   # Name of the image file
EXTRACT_DIR="/tmp/usbboot" # Directory to mount the image
DEST_DIR="$(pwd)/newflas"  # Destination directory for files (absolute path)
INITRD_DEST="$(pwd)/initrd" # Directory to extract initrd.img (absolute path)
LOOP_DEVICE=""             # Loop device

# Ensure the image file exists
if [ ! -f "$IMAGE_FILE" ]; then
    echo "[ERROR] Image file $IMAGE_FILE does not exist."
    exit 1
fi

# Create necessary directories
mkdir -p "$EXTRACT_DIR" "$DEST_DIR" "$INITRD_DEST"

# Set up a loop device for the image
echo "[INFO] Setting up loop device for $IMAGE_FILE..."
LOOP_DEVICE=$(losetup --show -fP "$IMAGE_FILE") || {
    echo "[ERROR] Failed to create loop device for $IMAGE_FILE."
    exit 1
}

# Mount the image
echo "[INFO] Mounting $IMAGE_FILE to $EXTRACT_DIR..."
mount "${LOOP_DEVICE}" "$EXTRACT_DIR" || {
    echo "[ERROR] Failed to mount $IMAGE_FILE."
    losetup -d "$LOOP_DEVICE"
    exit 1
}

# Copy the files to the destination directory
echo "[INFO] Copying files from $IMAGE_FILE to $DEST_DIR..."
cp -r "$EXTRACT_DIR"/* "$DEST_DIR/" || {
    echo "[ERROR] Failed to copy files from $EXTRACT_DIR."
    umount "$EXTRACT_DIR"
    losetup -d "$LOOP_DEVICE"
    exit 1
}

# Unmount the image and detach the loop device
echo "[INFO] Unmounting $EXTRACT_DIR and detaching loop device..."
umount "$EXTRACT_DIR"
losetup -d "$LOOP_DEVICE"

# Extract initrd.img if it exists
INITRD_FILE="$DEST_DIR/initrd.img"
echo "[DEBUG] Looking for initrd.img at: $INITRD_FILE"
if [ -f "$INITRD_FILE" ]; then
    echo "[INFO] Extracting initrd.img to $INITRD_DEST..."
    mkdir -p "$INITRD_DEST"
    cd "$INITRD_DEST"
    if file "$INITRD_FILE" | grep -q 'XZ compressed'; then
        xzcat "$INITRD_FILE" | cpio -idmv || {
            echo "[ERROR] Failed to extract XZ-compressed initrd.img."
            exit 1
        }
    else
        cpio -idmv < "$INITRD_FILE" || {
            echo "[ERROR] Failed to extract plain initrd.img."
            exit 1
        }
    fi
    cd - >/dev/null
else
    echo "[ERROR] initrd.img not found in $DEST_DIR. Please check the source files."
    exit 1
fi

# Cleanup
rm -rf "$EXTRACT_DIR"
echo "[INFO] Files extracted successfully from $IMAGE_FILE to $DEST_DIR."
