#!/usr/bin/env sh
# @(#)🏠📂 HOMEDIR	sh/diffio.sh	2026-04-05T19:29:49Z
# SPDX-FileCopyrightText: 2026 Lady <https://www.ladys.computer/about/#lady>
# SPDX-License-Identifier: MPL-2.0

## ⁌ An input~output transformation diff script
##
## ∎ Copyright © 2026 Lady [@ Ladys Computer].
##
## ⋮ This Source Code Form is subject to the terms of the Mozilla
##   Public License, version 2.0.
## If a copy of the M·P·L was not distributed with this file, You can
##   obtain one at {🔗<https://mozilla.org/MPL/2.0/>}.
##
## Usage :⁠—
##
## »|sh$sh diffio.sh testname
##
## This script diffs the result of transforming the provided test with
##   its expected output.
##
## It is an error if no test name is provided.

set -o 'errexit'

## § Configuration
##
## All of the commands used by this script are overridable with your
##   own implementations by setting the corresponding `cmd_COMMAND´
##   variable.

: "${cmd_CMP:=cmp}"
: "${cmd_BASENAME:=basename}"
: "${cmd_DIFF:=diff}"
: "${cmd_PRINTF:=printf}"
: "${cmd_PWD:=pwd}"
: "${cmd_REALPATH:=realpath}"
: "${cmd_SED:=sed}"
: "${cmd_TEST:=test}"
: "${cmd_TR:=tr}"

## By default, tests are assumed to be located in the `TESTING´
##   subdirectory of the current directory.
## This can be overridden by setting the `path_TESTDIR´ environment
##   variable.

realpwd="$(
  "${cmd_PWD}" -P
)"
defaulttestdir="${realpwd}"'/TESTING'
: "${path_TESTDIR:=${defaulttestdir}}"

## The default transformation command is assumed to be located in
##   `bin/${programname}´, where `${programname}´ is determined by
##   Ascii‐lowercasing the current directory name.
## This can be overridden by setting the `cmd_TRANSFORM´ environment
##   variable.

programname="$(
  "${cmd_BASENAME}" -- "${realpwd}" |
  "${cmd_TR}" 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'
)"
defaulttransform="${realpwd}"'/bin/'"${programname}"
: "${cmd_TRANSFORM:=${defaulttransform}}"

## Input files are read from `📥´ and expected output is read from
##   `📤´.
## These locations (relative to `${path_TESTDIR}´) can be customized by
##   setting the `name_INPUT´ and `name_OUTPUT´ variables,
##   respectively.
## If an input file exists but there is no corresponding output, the
##   transform is expected to error.

: "${name_INPUT:=📥}"
: "${name_OUTPUT:=📤}"

## § Implementation

inputfile="${path_TESTDIR}"'/'"${name_INPUT}"'/'"${1}"
outputfile="${path_TESTDIR}"'/'"${name_OUTPUT}"'/'"${1}"

## If no test name was provided, or the input file does not exist, it
##   is an error.

if "${cmd_TEST}" -z "${1}"
then :
  "${cmd_PRINTF}" '%s\n' "diffio: No name specified."
  exit 8
elif ! "${cmd_TEST}" -f "${inputfile}"
then :
  "${cmd_PRINTF}" '%s\n' "diffio: Input file not found."
  exit 9
fi

## If there is no output file, it is treated as empty.

if ! "${cmd_TEST}" -f "${outputfile}"
then :
  outputfile=/dev/null
fi

## The transformed output is diffed with the result.

"${cmd_TRANSFORM}" <"${inputfile}" |
"${cmd_DIFF}" -U 1 "${outputfile}" - |
"${cmd_SED}" '1,2d'
