#!/bin/sh
#
# unpatch - re-generate patch from files and their .orig copy
#
# usage: unpatch [-g] [-pN] FILES...

STRIP=0
PREFIX_A=
PREFIX_B=
ORIG=".orig"
while getopts 'hgp:' opt; do
  # shellcheck disable=SC2249
  case "${opt}" in
    h)
      sed -n '/^# usage/,/^[^#]/{/^[^#]/!{s/^#[ ]\?//p}}' <"$0"
      exit 0
      ;;
    g)
      PREFIX_A=a/
      PREFIX_B=b/
      ORIG=
      ;;
    p)
      STRIP=${OPTARG}
      ;;
    ?)
      sed -ne '/^#/!q;s/.\{1,2\}//;1d;p' <"$0" 1>&2
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

pstrip() {
  i=0
  p="$1"
  while [ "${i}" -lt "${STRIP}" ]; do
    i=$((i + 1))
    p=${p#*/}
  done
  printf %s "${p}"
}

match() {
  case "$1" in
    "$2") true ;;
    *) false ;;
  esac
}

if [ "$#" -eq 0 ]; then
  set -- .
  STRIP="$((STRIP + 1))"
fi

# shellcheck disable=SC2250,SC2312
for f; do
  if [ -f "${f}" ] && [ -f "$f.orig" ]; then
    diff -u --label "$PREFIX_A$(pstrip "$f$ORIG")" "${f}.orig" \
      --label "$PREFIX_B$(pstrip "$f")" "$f"
  elif match "${f}" "*.orig" && [ -f "${f}" ] && [ -f "${f%.orig}" ]; then
    diff -u --label "$PREFIX_A$(pstrip "${f%.orig}$ORIG")" "$f" \
      --label "$PREFIX_B$(pstrip "${f%.orig}")" "${f%.orig}"
  elif [ -d "${f}" ]; then
    find "${f}" -type f -name '*.orig' -exec "$0" ${PREFIX_A:+-g} "-p$STRIP" {} ';'
  else
    printf "Can't unpatch '%s'.\n" "$f" 1>&2
  fi
done
