#!/usr/bin/env python3

import re
import sys

# Dictionary of macros to replace: key is the macro, value is its replacement
MACROS_TO_REPLACE = {
    r'%make\b': '%make_build',
    r'%makeinstall_std\b': '%make_install',
    r'%configure2_5x\b': '%configure',
    r'%apply_patches\b': '%autopatch -p1',
    r'\$\{?RPM_BUILD_ROOT\}?': '%{buildroot}',
    # Add more macros here as needed
    # Example:
    # r'%old_macro\b': '%new_macro',
}

def replace_macros_and_clean(file_path):
    try:
        # Read the file content
        with open(file_path, 'r') as file:
            original_content = file.read()
        content = original_content

        # Track changes
        changes = []

        # Replace macros using the dictionary
        for old_macro, new_macro in MACROS_TO_REPLACE.items():
            # Use regex to replace only whole macros
            new_content, count = re.subn(old_macro, new_macro, content)
            if count > 0:
                changes.append(f"Replaced '{old_macro}' with '{new_macro}' {count} times")
            content = new_content

        # Remove trailing spaces from each line
        lines = content.splitlines()
        cleaned_lines = [line.rstrip() for line in lines]
        cleaned_content = "\n".join(cleaned_lines) + "\n"  # Ensure trailing newline

        # Check if trailing spaces were removed
        if cleaned_content != content:
            changes.append("Removed trailing spaces from all lines")

        # Check if any changes were made
        if changes:
            # Write the modified content back to the file
            with open(file_path, 'w') as file:
                file.write(cleaned_content)
            print(f"Changes in file '{file_path}':")
            for change in changes:
                print(f"  - {change}")
        else:
            print(f"Nothing to clean in file '{file_path}'.")
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: /usr/bin/spec-cleaner foo.spec")
    else:
        file_path = sys.argv[1]
        replace_macros_and_clean(file_path)
