#!/bin/bash

# Check if the script is run with root privileges
if [ "$EUID" -ne 0 ]; then
    echo "This script must be run with root privileges."
    exit 1
fi

updatedb

# Check if .pacnew files exist and run vimdiff
locate_pattern="*.pacnew"
pacnew_files=$(locate "$locate_pattern")

# Check if any .pacnew files were found
if [ -z "$pacnew_files" ]; then
    echo ":: No pacnew files found. Exiting..."
    echo

    exit 1
fi

echo "Press any key to begin processing..."

# Run vimdiff for each .pacnew file
for pacnew_file in $pacnew_files; do
    read -n 1 -s -r -p "> $pacnew_file"
    echo

    original_file="${pacnew_file%.pacnew}"

    if [ -f "$pacnew_file" ]; then
        vimdiff "$original_file" "$pacnew_file"
        echo "Ran vimdiff for $original_file and $pacnew_file"
    else
        echo ":: File not found. Skipping..."
        echo

        continue
    fi

    # Prompt user to confirm before removing the pacnew file
    read -p "Do you want to Delete, Replace original, or Skip the $pacnew_file? [d/r/S]: " buffer

    buffer_l=$(echo "$buffer" | tr '[:upper:]' '[:lower:]')

    if [ "$buffer_l" = "d" ]; then
        rm "$pacnew_file"

        echo ":: Removed $pacnew_file"
    elif [ "$buffer_l" = "r" ]; then
        mv "$pacnew_file" "$original_file"

        echo ":: Replaced $original_file with $pacnew_file"
    else
        echo ":: Skipped $pacnew_file"
    fi

    echo
done

updatedb

