#!/bin/bash

## Copyright (C) 2026 - 2026 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## AI-Assisted

## Safe git external diff driver: prints a TEXTUAL diff, but neutralized for
## the terminal via 'stcat' (a hostile blob cannot inject terminal escape
## sequences). Used by dm-review-branch.

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

# shellcheck source=../../../../helper-scripts/usr/libexec/helper-scripts/has.sh
source "${HELPER_SCRIPTS_PATH:-}"/usr/libexec/helper-scripts/has.sh

has stcat
has unicode-show

git_review_self="$(readlink -f -- "${BASH_SOURCE[0]}")"
review_tool="git-diff-review"

## This display is capable of safely displaying content that triggered fatal
## errors in unicode-show.
git_review_display_fatal_content='true'

## Invoked indirectly by the sourced git-review-driver.sh (not dead code).
# shellcheck disable=SC2317
display_regular_file() {
  ## stcat neutralizes terminal escapes in a hostile blob. Accept only 'diff'
  ## exit 0/1 (same/differ); a real diff error (>=2) or any stcat failure
  ## must NOT pass as a rendered file.
  local diff_rc diff_out

  printf '%s\n' "--- diff (stcat-neutralized) for ${3} ---"
  diff_rc=0
  diff_out="$(diff --unified -- "${1}" "${2}")" || diff_rc=$?
  if [ "${diff_rc}" -gt 1 ]; then
    printf '%s\n' "git-diff-review: ERROR: diff failed (rc='${diff_rc}') for '${3}'." >&2
    return "${diff_rc}"
  fi
  printf '%s\n' "${diff_out}" | stcat || diff_rc=$?
  if [ "${diff_rc}" -ne 0 ]; then
    printf '%s\n' "git-diff-review: WARNING: stcat failed (rc='${diff_rc}') for '${3}'. Piping into unicode-show..." >&2
    printf '%s\n' "${diff_out}" | unicode-show || true
    ## TODO: Allow continue. Useful in case of harmless unicode.
    ## <stdin>:6: [U+0020]
    ##  -> ' ' (U+0020, SPACE, Zs)
    #printf '%s\n' "git-diff-review: QUESTION: continue y/n?"
    #read -r continue_yes_no || printf '%s\n' "git-diff-review: ERROR: bash 'read' failed."
    #printf '%s\n' "git-diff-review: continue_yes_no: '${continue_yes_no}'"
    #if ! [ "${continue_yes_no,,}" = "y" ]; then
    #  return "${diff_rc}"
    #fi
  fi
}

# shellcheck source=../libexec/developer-meta-files/git-review-driver.sh
source /usr/libexec/developer-meta-files/git-review-driver.sh
