#!/usr/bin/env bash
#
# $Id: prtrej,v 1.4 2023/12/21 01:30:00 jmq Exp $
# (c) 2002 by Markus Ackermann <maol@symlink.ch>
# (c) 2003,2004 by Martin Opel <mo@obbl-net.de>
# (c) 2023,2024 by John McQuah
#
# may be redistributed and modified under the terms of the GPL
# only usable with CRUX Linux, version 0.9.2 or higher
#
# USE AT YOUR OWN RISK
#
# Interactive tool to ask user what he/she wants to do with a rejected file
# in /var/lib/pkg/rejected
# Requires opt/dialog to be installed
# All identical files are removed without a user's interaction

TMP=$(mktemp -p "${TMPDIR:-/tmp}" prtrej.XXXXXXXX)
REJ=/var/lib/pkg/rejected

cleanup() {
  [ "$count" = 0 ] || echo "Removed $count unneeded files"
  rm -f "$TMP"
}

interrupted() {
  echo "Interrupted..."
  cleanup
  exit 1
}

trap "interrupted" SIGHUP SIGINT SIGQUIT SIGTERM

count=0

if [ ! -d "$REJ" ]; then
  echo "$REJ not found. Exiting"
  exit 1
fi

while read -r reject; do
  real="/${reject#*rejected/}"
  #
  # Insert a test to ensure that diff is given two valid args.
  # Nonexistent $real suggests that $reject is no longer needed.
  #
  if [ -e "$real" ] && cmp -s "$real" "$reject"; then
    rm "$reject"
    count=$(( count + 1 ))
    ACTION=NOOP
  elif [ ! -e "$real" ]; then
    ACTION=$(dialog --no-shadow --stdout \
    --title "$real not associated with any currently installed package" \
    --textbox "$reject" -1 -1 \
    --menu "Make your selection:" 11 50 4 \
    INST "Restore to original location." \
    KEEP "Delete." \
    EXIT "Exit immediately." \
    "  " "Do nothing now.")
  else
    diff -u "$real" "$reject" &> "$TMP"

    ACTION=$(dialog --no-shadow --stdout \
    --title "diff $real $reject" \
    --textbox "$TMP" -1 -1 \
    --menu "Make your selection:" 11 50 4 \
    KEEP "Keep existing file." \
    INST "Overwrite with file from package." \
    EXIT "Exit immediately." \
    "  " "Do nothing now.")
  fi
    
  case "$ACTION" in
      KEEP)
         echo "Removing $reject."
         rm "$reject"
         ;;
      INST)
         echo "Moving $reject to $(dirname "$real")."
         mv "$reject" "$real"
         ;;
      EXIT)
         echo "Exiting..."
         cleanup
         exit 0
         ;;
      NOOP)
         ;;
      *)
         echo "Leaving $real and $reject untouched for now."
         ;;
   esac
done < <(find "$REJ" -type f)

cleanup
