#!/bin/sh
set -eu
export LC_ALL=C.UTF-8
export SOURCE_DATE_EPOCH={{ SOURCE_DATE_EPOCH }}

case {{ FORMAT }} in tar | squashfs | ext2 | ext4 | erofs | cpio) : ;; *) exit 1 ;; esac

# The exit trap needs a -r because for unknown formats, mmdebstrap will produce
# a directory as output. We do not supply --format={{ FORMAT }} because we also
# want to test whether mmdebstrap automatically picks the right format
# depending on the output filename.
trap "rm -rf /tmp/debian-chroot-{{ MODE }}.{{ FORMAT }}" EXIT INT TERM

case {{ MODE }} in unshare | fakechroot) : ;; *) exit 1 ;; esac

if [ ! -e "./cache/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }}" ]; then
  echo "E: ./cache/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }} does not exist" >&2
  echo "E: Run the 'mmdebstrap' test first" >&2
  exit 1
fi

prefix=
if [ "$(id -u)" -eq 0 ] && [ "{{ MODE }}" != "root" ] && [ "{{ MODE }}" != "auto" ]; then
  if ! id "${SUDO_USER:-user}" >/dev/null 2>&1; then
    if [ ! -e /mmdebstrap-testenv ]; then
      echo "this test modifies the system and should only be run inside a container" >&2
      exit 1
    fi
    useradd --home-dir "/home/${SUDO_USER:-user}" --create-home "${SUDO_USER:-user}"
  fi
  prefix="runuser -u ${SUDO_USER:-user} --"
fi

$prefix {{ CMD }} --mode={{ MODE }} --variant={{ VARIANT }} {{ DIST }} /tmp/debian-chroot-{{ MODE }}.{{ FORMAT }} {{ MIRROR }}
# For unknown formats, the created output will be of type directory. We error
# out early, to avoid running cmp and diffoscope on output that is wrong
# anyways. We don't add --format={{ FORMAT }} above because we want to test
# whether the format gets chosen automatically.
if [ ! -f "./cache/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }}" ]; then
  echo "E: not a regular file: ./cache/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }}" >&2
  exit 1
fi
cmp ./cache/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }} /tmp/debian-chroot-{{ MODE }}.{{ FORMAT }} \
  || diffoscope ./cache/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }} /tmp/debian-chroot-{{ MODE }}.{{ FORMAT }}

# we cannot test chrootless mode here, because mmdebstrap relies on the
# usrmerge package to set up merged-/usr and that doesn't work in chrootless
# mode
