#!/bin/bash

# =============================
# Script to Compact ./initrd into ./newflas/initrd.img
# =============================

# Configuration
INITRD_DIR="./initrd"       # Directory containing extracted initrd contents
OUTPUT_DIR="./newflas"      # Directory to store the compressed initrd.img
OUTPUT_FILE="$OUTPUT_DIR/initrd.img" # Full path to the output file

# Ensure the initrd directory exists
if [ ! -d "$INITRD_DIR" ]; then
    echo "[ERROR] Directory $INITRD_DIR does not exist."
    exit 1
fi

# Ensure the output directory exists
if [ ! -d "$OUTPUT_DIR" ]; then
    echo "[INFO] Creating output directory $OUTPUT_DIR..."
    mkdir -p "$OUTPUT_DIR" || {
        echo "[ERROR] Failed to create directory $OUTPUT_DIR."
        exit 1
    }
fi

# Remove any existing initrd.img
if [ -f "$OUTPUT_FILE" ]; then
    echo "[INFO] Removing existing $OUTPUT_FILE..."
    rm -f "$OUTPUT_FILE" || {
        echo "[ERROR] Failed to remove existing $OUTPUT_FILE."
        exit 1
    }
fi

# Compact the initrd directory into initrd.img
echo "[INFO] Creating compressed initrd.img from $INITRD_DIR..."
(
    cd "$INITRD_DIR" || {
        echo "[ERROR] Failed to change directory to $INITRD_DIR."
        exit 1
    }
    # Use the absolute path for OUTPUT_FILE when inside INITRD_DIR
    find . | cpio -o -H newc | xz -C crc32 > "../$OUTPUT_FILE" || {
        echo "[ERROR] Failed to create $OUTPUT_FILE during compression."
        exit 1
    }
)

# Verify the output file
if [ -f "$OUTPUT_FILE" ]; then
    echo "[INFO] initrd.img created successfully at $OUTPUT_FILE."
else
    echo "[ERROR] initrd.img was not created. Check for errors."
    exit 1
fi
