#!/bin/sh

# script to update patches on a machine. See usage() below
# Written by Philip Brown

# shellcheck disable=SC2250

patchdir=$(dirname "$0")
cd "$patchdir" || exit

usage() {
  cat <<EOF
 usage: patchupdate [-R /root/dir]
 patchupdate uses patchcompare -l to figure out what patches are downrev,
  and will then install them, using the patch_order file in the
 same directory as patchupdate
 (currently $patchdir)
This means that you should copy this program into the same
directory as your patches, before using it.
You will also need 'patchcompare' there.
(You may want to use symlinks, over multiple copies)
EOF
}

if [ "$1" = "-h" ]; then
  usage
  exit
fi

if [ "$1" = "-R" ]; then
  ROOTARGS="$1 $2"
  shift
  shift
fi

if [ ! -f patch_order ]; then
  print ERROR: need a patch_order file
  exit 1
fi

######################################################################
# End of prep work. real stuff starts here

TMPFILE=/tmp/patchupdate.$$
rm -f "$TMPFILE"
touch "$TMPFILE"

./patchcompare "$ROOTARGS" -l | awk -F: '{print $1}' >"$TMPFILE"
count=$(wc -w "$TMPFILE")
if [ ! -s "$TMPFILE" ]; then
  print No patches to add
  rm "$TMPFILE"
  exit 0
else
  printf '%s\n' "Attempting to apply $count patches"
fi

# shellcheck disable=SC2312
patchadd "$ROOTARGS" -M . "$(grep -F -f "$TMPFILE" patch_order)"

rm "$TMPFILE"
