#!/bin/bash

# SCRIPT: remove_ldap_entry.sh
# DESCRIPTION: Safely removes the specific 'dn: dc=nodomain' entry block from an LDIF file
#              and ensures proper blank line separation and cleanup for slapadd import.

# --- Configuration ---
# Target entry to remove (The DN of the placeholder entry)
TARGET_DN="dn: dc=nodomain"

# --- Functions ---

# Function to display usage information
usage() {
    echo "Usage: $0 <path/to/backup.ldif>"
    echo "This script cleans the specified LDIF file for proper slapadd use."
    exit 1
}

# Function to remove the entry using awk
remove_entry() {
    local ldif_file="$1"
    local temp_file="${ldif_file}.tmp"
    local entry_found=0

    echo "Processing LDIF file: ${ldif_file}"

    # --- STEP 1: NORMALIZE LINE ENDINGS (Fixes cross-OS file transfer issues) ---
    echo "Attempting to normalize line endings (removing carriage returns \r)..."
    # Removes all Windows/DOS carriage returns (\r) to ensure strict Unix line endings.
    sed 's/\r$//' "$ldif_file" > "$temp_file"
    mv "$temp_file" "$ldif_file"
    echo "Line endings normalized."

    # --- STEP 2: AGGRESSIVE CONTENT CLEANUP (Resolves 'empty AttributeDescription' error) ---
    echo "Aggressively cleaning, trimming, and removing spurious lines..."
    
    # NEW FIX: Remove all non-printable ASCII control characters (excluding common whitespace)
    # This targets invisible garbage that causes parser failure.
    # Note: Requires GNU sed for \xNN syntax, which is standard in most Linux distributions.
    sed -i 's/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]//g' "$ldif_file"
    
    # 1. Remove leading whitespace from all lines (s/^[[:space:]]*//) 
    # 2. Filter out any lines that are now completely empty (grep -v '^[[:space:]]*$')
    sed 's/^[[:space:]]*//' "$ldif_file" | grep -v '^[[:space:]]*$' > "$temp_file"
    mv "$temp_file" "$ldif_file"
    echo "Invisible control characters, leading whitespace, and spurious blank lines cleaned."

    # --- STEP 3: ENFORCE BLANK LINES (Resolves "multiple DNs" error) ---
    echo "Attempting to enforce robust blank line separation using awk..."
    # The AWK command below inserts a blank line before every line that starts with 'dn:' 
    # (except the very first line of the file, which should not be preceded by a blank line).
    awk '
    {
      # If the current line starts with "dn:" and we are past the first line of the file, insert a blank line.
      if (NR > 1 && $0 ~ /^dn:/) {
        print ""
      }
      print
    }
    ' "$ldif_file" > "$temp_file"
    mv "$temp_file" "$ldif_file"
    echo "Blank line fix applied."

    # --- STEP 4: REMOVE TARGET ENTRY (Original logic to remove dc=nodomain) ---
    
    # Check if the target entry exists before attempting removal
    if grep -q "^${TARGET_DN}$" "$ldif_file"; then
        entry_found=1
    fi
    
    # If the target is found, we proceed with AWK removal.
    if [ "$entry_found" -eq 1 ]; then
        echo "Placeholder entry '${TARGET_DN}' found. Removing entire block..."

        # Awk command explanation:
        # RS = "": Treats each block separated by a blank line as a single record (LDIF entry).
        awk -v target_dn="$TARGET_DN" '
        BEGIN { RS = "" ; FS = "\n" }
        {
          if ($1 !~ "^" target_dn) {
            print $0
            printf RS
          }
        }
        ' "$ldif_file" > "$temp_file"

        if [ $? -eq 0 ]; then
            # Overwrite the original file with the cleaned content
            mv "$temp_file" "$ldif_file"
            echo "Success: Entry '${TARGET_DN}' has been removed from ${ldif_file}."
        else
            echo "Error: Awk command failed. Original file remains untouched."
            rm -f "$temp_file"
            return 1
        fi
    else
        echo "Success: Target entry '${TARGET_DN}' was not found in the file. Proceeding with clean file."
    fi

    # --- STEP 5: STRIP OPERATIONAL ATTRIBUTES (Crucial for slapadd) ---
    # This removes all internal metadata (timestamps, CSN, UUIDs) that slapadd must regenerate.
    echo "Stripping operational metadata attributes..."
    grep -vE '^(creatorsName:|createTimestamp:|entryCSN:|modifiersName:|modifyTimestamp:|entryUUID:|structuralObjectClass:)' "$ldif_file" > "$temp_file"
    mv "$temp_file" "$ldif_file"
    echo "Metadata stripped."
    
    # Clean up any leftover temporary files
    rm -f "$temp_file"
    
    echo "LDIF file is ready. You can now attempt the slapadd command."
}

# --- Main Execution ---

# Check for required argument
if [ -z "$1" ]; then
    usage
fi

# Store the file path
LDIF_FILE="$1"

# Check if the file exists
if [ ! -f "$LDIF_FILE" ]; then
    echo "Error: File not found at '${LDIF_FILE}'."
    exit 1
fi

# Run the removal function
remove_entry "$LDIF_FILE"