#!/bin/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 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
# TODO: respect SYSROOT?

TMP=/tmp/rejdiff
REJ=/var/lib/pkg/rejected

cleanup() {
  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

mapfile -t REJECTS < <(find $REJ -type f)
# Why not loop over the output of find?
# bash splits on whitespace, so by putting the newline-separated results
# of find into an array, we can use double-quotes to ensure any file with
# space in its name is not misinterpreted as multiple files.
# Redefining IFS is another option, but prone to unwanted side-effects.

for reject in "${REJECTS[@]}"; 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.
  # Forgot to merge it, and then later uninstalled the package, perhaps?
  # If this circumstance is common and $REJ becomes cluttered too easily, 
  # then someone might ask for another side-effect of prt-get remove.
  # This cleanup could be incorporated directly into pkgrm, but until that
  # happens we might as well do the cleanup here.
  #
  if [ ! -e "$real" ] || cmp -s "$real" "$reject"; then
    rm "$reject"
    count=$(( count + 1 ))
  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.")
    
    case "$ACTION" in
      "KEEP")
         echo "Keeping old file, removing $reject."
         rm $reject
         ;;
      "INST")
         echo "Installing new file, overwriting $real with $reject."
         mv $reject $real
         ;;
      "EXIT")
         echo "Exiting..."
         cleanup
         exit 0
         ;;
      *)
         echo "Leaving $real and $reject untouched for now."
         ;;
     esac
  fi
done

cleanup
