#!/bin/bash

# Ensure the script is run as root
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

echo "--- Starting RHEL image cleanup script ---"

# 1. Clean Cloud-init artifacts and logs
# This forces cloud-init to treat the next boot as the first boot.
echo "Cleaning cloud-init state and logs..."
cloud-init clean --logs --machine-id --configs all
# The 'cloud-init clean' command handles the removal of data in /var/lib/cloud/
# but you can explicitly remove them as well to be certain:
rm -rf /var/lib/cloud/instances/*
rm -rf /var/lib/cloud/instance
rm -rf /var/lib/cloud/data/*
echo "Cloud-init cleaned."

# 2. Remove SSH host keys
# This forces the generation of new unique host keys on the first boot of a new instance.
echo "Removing SSH host keys..."
rm -f /etc/ssh/ssh_host_*
echo "SSH host keys removed."

# 3. Remove other unique system identifiers
# Unregister from Red Hat Subscription Manager if the image was registered for updates
echo "Unregistering from Red Hat Subscription Manager (if applicable)..."
subscription-manager unregister
subscription-manager clean
echo "System unregistered."

# Function definition for history cleanup (put this near the top of the script)
function clear_all_histories() {
    echo "Clearing bash histories for all users..."
    for dir in /root /home/*; do
        if [ -d "$dir" ]; then
            if [ -f "$dir/.bash_history" ]; then
                echo "  Clearing history for user in $dir"
                # Truncate the file content, preserving permissions/ownership
                truncate -s 0 "$dir/.bash_history"
            fi
        fi
    done
    # Clear history for the current root session running the script
    history -c
    echo "All histories cleared."
}

# Remove the existing machine-id file (cloud-init clean --machine-id might handle this, but it doesn't hurt to be explicit for older systems)
echo "Removing machine-id..."
truncate -s 0 /etc/machine-id

# Clean network interface specific configurations (e.g., HWADDR, UUID)
# This is crucial for environments like VMware or KVM where MAC addresses change on cloning.
echo "Cleaning network configuration files..."
sed -i '/^\(HWADDR\|UUID\)=/d' /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null
sed -i '/^\(connection\|ethernet\).uuid/d' /etc/NetworkManager/system-connections/* 2>/dev/null
sed -i '/^\(connection\|ethernet\).mac-address/d' /etc/NetworkManager/system-connections/* 2>/dev/null
rm -f /etc/udev/rules.d/70-persistent-net.rules 2>/dev/null
echo "Network configurations cleaned."

# 4. Clean up logs and temporary files
echo "Cleaning logs and temporary files..."
rm -rf /tmp/*
cat /dev/null > /var/log/cloud-init.log
cat /dev/null > /var/log/cloud-init-output.log
for f in /var/log/*.log; do cat /dev/null > $f; done
rm -rf /var/cache/dnf/*
rm -rf /var/cache/yum/*
echo "Logs and temporary files cleaned."
clear_all_histories
history -c && history -w
echo "--- Image cleanup complete. You can now shut down the VM and create your template/image. ---"

