#!/bin/sh
#
# dndcmp.sh
# Drag'n'drop comparator
#
# Compares two files which are drag'n'dropped onto the companion file
# dndcmp.desktop. That way all user I/O happens in a GUI fashion by
# means of zenity dialogs. Nevertheless this shell script could be
# executed from the command line as well.
#

# Check number of input arguments
if [ $# -eq 1 ]
then
    # Only one input argument. Open file selection dialog to let the user
    # pick the second file
    file1="$1"
    file2=$(zenity --file-selection --title="Please pick the second file")
    if [ $? -ne 0 ]
    then
        # Abort script if file selection dialog was aborted
        zenity --error --text="Two files required for comparison."
        exit 1
    fi
elif [ $# -eq 2 ]
then
    # Two input arguments
    file1="$1"
    file2="$2"
else
    # Neither one nor two input arguments. Abort script
    zenity --error --text="Please drag'n'drop one or two files."
    exit 1
fi

# Make sure both inputs are regular files
if [ ! -f "$file1" ]
then
    zenity --error --text="$file1 is not a file."
    exit 2
fi
if [ ! -f "$file2" ]
then
    zenity --error --text="$file2 is not a file."
    exit 2
fi

# Now do the actual comparison and inform the user about its result
cmp --quiet "$file1" "$file2"
  # exit status:
  # 0 - same
  # 1 - different
  # 2 - trouble
case $? in
    0) zenity --title="Comparison result" --info \
           --text="Both files contain the same data:\n$file1\n$file2"
       ;;
    1) zenity --title="Comparison result" --warning \
           --text="The two files differ:\n$file1\n$file2"
       ;;
    *) zenity --title="Comparison result" --error \
           --text="An error occurred while comparing the files:\n$file1\n$file2"
       ;;
esac
