#!/bin/bash

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

## Exit non-zero after the first failed plugin.

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

# shellcheck source=../libexec/helper-scripts/log_run_die.sh
source /usr/libexec/helper-scripts/log_run_die.sh

log_level=info

run_plugin_command() {
  declare -g plugin_cmd
  local plugin_args

  plugin_cmd="$1"
  shift
  plugin_args=( "$@" )

  if (( ${#plugin_args[@]} == 0 )); then
    ## captured_stdin inherited from text_safety_scan function.
    "${plugin_cmd}" < "${captured_stdin_file}"
  else
    "${plugin_cmd}" "${plugin_args[@]}"
  fi

  log info "${plugin_cmd} OK"
  unset plugin_cmd
}

cleanup() {
  local _exit_code="${1:-$?}"
  trap - EXIT
  trap - ERR
  if [ -n "${captured_stdin_file-}" ]; then
    safe-rm --force --verbose -- "${captured_stdin_file}"
  fi
  if [ "$_exit_code" = "0" ]; then
    log notice "OK"
  else
    log error "FAIL"
  fi
  exit "${_exit_code}"
}

error_handler() {
  local _exit_code="${1:-$?}"
  trap - ERR
  log error "FAILED: ${plugin_cmd-"${BASH_COMMAND}"}"
  exit "${_exit_code}"
}

trap "cleanup" EXIT

trap "error_handler" ERR

text_safety_scan() {
  declare -g captured_stdin_file
  local file_list file_name plugin_list plugin_item

  file_list=( "$@" )
  plugin_list=( 'unicode-show' 'modeline-show' )

  if (( ${#file_list[@]} == 0 )); then
    if ! [ -e '/proc/self/fd/0' ]; then
      die 1 'stdin is not open!'
    fi
    ## Using a temp file rather than capturing to a variable because Bash will
    ## strip trailing newlines from captured text, potentially distorting the
    ## results of the check.
    if ! captured_stdin_file="$(mktemp)"; then
      die 1 'Could not create temporary file for capturing stdin!'
    fi

    cat | sponge -- "${captured_stdin_file}"

    for plugin_item in "${plugin_list[@]}"; do
      run_plugin_command "${plugin_item}"
    done
  else
    for file_name in "${file_list[@]}"; do
      ## Leave handling if it is a readable file versus a folder to plugins.
      for plugin_item in "${plugin_list[@]}"; do
        run_plugin_command "${plugin_item}" "${file_name}"
      done
    done
  fi
}

text_safety_scan "$@"
