#!/bin/bash
# Cleanup script for old initrd files
# This script removes old initrd.img-*-rpi-2712 files, keeping only the one
# that matches the current linux-image-apollo package version

set -e

# Only run on aarch64 architecture
if [ "$(uname -m)" != "aarch64" ]; then
    exit 0
fi

version="$1"
image_path="$2"

# Only run on configure
eval set -- "$DEB_MAINT_PARAMS"
case "$1" in
  configure)
    ;;
  *)
    exit 0
    ;;
esac

# Use the version being installed (passed as parameter)
current_version="$version"

if [ -z "$current_version" ]; then
    echo "Warning: No version parameter provided, skipping initrd cleanup"
    exit 0
fi

echo "Installing linux-image-apollo version: $current_version"

# Find all initrd files matching the pattern
initrd_files=$(find /boot -maxdepth 1 -name "initrd.img-*-rpi-2712" -type f 2>/dev/null || true)

if [ -z "$initrd_files" ]; then
    echo "No initrd.img-*-rpi-2712 files found in /boot"
    exit 0
fi

# The initrd file we want to keep
keep_file="/boot/initrd.img-${current_version}"

echo "Keeping initrd file: $keep_file"

# Remove old initrd files
for initrd_file in $initrd_files; do
    if [ "$initrd_file" != "$keep_file" ]; then
        if [ -f "$initrd_file" ]; then
            echo "Removing old initrd file: $initrd_file"
            rm -f "$initrd_file"
        fi
    fi
done

echo "Initrd cleanup completed"
