#!/bin/bash

###############################################################################
## Modified Dell iDRAC firmware package - EXTRACT ONLY VERSION
## This script only extracts the archive contents without any firmware updates
###############################################################################

PACKAGENAME=$(basename "$0")
ORIGINAL_FILE="/Volumes/yyy/Downloads/id/iDRAC-with-Lifecycle-Controller_Firmware_WN31M_LN64_7.20.30.50_A00.BIN"
ARCHIVE_MARKER="#####Startofarchive#####"

# Check if original file exists
if [ ! -f "$ORIGINAL_FILE" ]; then
    echo "Error: Original firmware file not found at $ORIGINAL_FILE"
    exit 1
fi

echo "Extracting files from Dell iDRAC firmware package..."
echo "This script will ONLY extract files - no firmware updates will be performed."
echo ""

# Find the line number where the archive starts
ARCHIVE_LINE=$(grep -n "$ARCHIVE_MARKER" "$ORIGINAL_FILE" | tail -n1 | cut -d ":" -f 1)

if [ -z "$ARCHIVE_LINE" ]; then
    echo "Error: Could not find archive marker in firmware file"
    exit 1
fi

# Calculate the line after the marker
ARCHIVE_START=$((ARCHIVE_LINE + 1))

echo "Found archive at line $ARCHIVE_LINE"
echo "Extracting to current directory: $(pwd)"
echo ""

# Create temporary file for the archive
TEMP_ARCHIVE=$(mktemp /tmp/idrac_extract.XXXXXX)

# Extract the gzipped tar archive from the original file
tail -n +${ARCHIVE_START} "$ORIGINAL_FILE" > "$TEMP_ARCHIVE"

# Extract the contents
if command -v gzip >/dev/null 2>&1; then
    echo "Extracting archive contents..."
    gzip -dc "$TEMP_ARCHIVE" | tar -xf -
    
    if [ $? -eq 0 ]; then
        echo ""
        echo "Extraction completed successfully!"
        echo "Files extracted to: $(pwd)"
        echo ""
        echo "Extracted files:"
        ls -la
    else
        echo "Error: Failed to extract archive"
        rm -f "$TEMP_ARCHIVE"
        exit 1
    fi
else
    echo "Error: gzip command not found"
    rm -f "$TEMP_ARCHIVE"
    exit 1
fi

# Clean up temporary file
rm -f "$TEMP_ARCHIVE"

echo ""
echo "IMPORTANT: This extraction does not install or update any firmware."
echo "These are the files that would normally be used for firmware updates."