#!/bin/sh

set -eu

cd "$(dirname "$0")"

if [ $# -eq 0 ]; then
  # Run all if none specified
  set -- $(find . -name test -executable -exec dirname '{}' ';')
fi

export DEB_GREP_ENABLE_STRAY_BACKSLASH_WARN=1 # Ensure #1019326 is visible
export DEBIAN_FRONTEND=noninteractive
export UCF_TEST_TARGET="/tmp"
export UCF_TEST_BINDIR="${UCF_TEST_BINDIR=../../}"
export UCF_TEST_LIBDIR="${UCF_TEST_LIBDIR=../../}"
export DPKG_ROOT="$(mktemp -d)"
export PATH="$DPKG_ROOT/bin:$PATH"

report() {
  total=$1
  rm -rf "$DPKG_ROOT"
  cat <<EOF
Testsuite (DPKG_ROOT) report:
  Success: ${success:=0}
  Skipped: ${skip:=0}
  Failed: $(($1 - success - skip))
  TOTAL: $total
EOF
  [ $((success + skip)) -eq "$total" ] # set exit status
}

trap 'report $#' EXIT

success=0
skip=0
for tdir; do
  echo "Running $tdir" >&2

  mkdir -p "$DPKG_ROOT/tmp" "$DPKG_ROOT/bin" "$DPKG_ROOT/var/lib/ucf" "$DPKG_ROOT/var/lib/dpkg/info" "$DPKG_ROOT/usr/share/debconf" "$DPKG_ROOT/var/cache/debconf"
  # create fake "id" utility to fake that we are root
  cat <<'END' >"$DPKG_ROOT/bin/id"
#!/bin/sh
echo 0
END
  chmod +x "$DPKG_ROOT/bin/id"

  # set up debconf inside $DPKG_ROOT
  cp -a /usr/share/debconf/confmodule /usr/share/debconf/debconf.conf "$DPKG_ROOT/usr/share/debconf"

  if [ -z "${AUTOPKGTEST_TMP:-}" ]; then
      po2debconf ../debian/templates > "$DPKG_ROOT/var/lib/dpkg/info/ucf.templates"
  else
      # If used as autopkgtest, use installed templates.
      cat "$(dpkg-query --root=/ --control-path ucf templates)" >"$DPKG_ROOT/$(dpkg-query --root=/ --control-path ucf templates)"
  fi

  cat <<'END' >"$DPKG_ROOT/var/lib/dpkg/status"
Package: ucf
Status: install ok installed
Architecture: all
Version: 3.0054
Description: Update Configuration File(s): preserve user changes to config files
Maintainer: Mark Hindley <leepen@debian.org>
END

  { ret=0; env --chdir="$tdir" ./test 2>&1 || ret=$?; echo "exit: $ret"; } | diff -u "$tdir/expected/output" -
  if [ -d "$tdir/expected/target" ]; then
    diff -urN "$tdir/expected/target" "$DPKG_ROOT/$UCF_TEST_TARGET"
  fi
  if [ -d "$tdir/expected/state" ]; then
    diff -urN "$tdir/expected/state" "$DPKG_ROOT/var/lib/ucf"
  fi
  success=$((success + 1))

  rm -rf "$DPKG_ROOT"
done
