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

[ "$(id -u)" -eq 0 ]
[ {{ MODE }} = "root" ]
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/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }}" EXIT INT TERM

# First perform smoke check and then move to ./cache. This is to make sure that
# we don't store broken output. The exit trap will clean up /tmp if below
# failed
{{ CMD }} --mode={{ MODE }} --variant={{ VARIANT }} {{ DIST }} /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }} {{ MIRROR }}
if [ "{{ FORMAT }}" = tar ]; then
  printf 'ustar\0' | cmp --bytes=6 --ignore-initial=257:0 /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.tar -
elif [ "{{ FORMAT }}" = squashfs ]; then
  printf 'hsqs' | cmp --bytes=4 /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.squashfs -
elif [ "{{ FORMAT }}" = ext2 ]; then
  printf '\123\357' | cmp --bytes=2 --ignore-initial=1080:0 /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.ext2 -
  printf '\000\000\000\000\000\000\000\000\000\000\000\000' | cmp --bytes=12 --ignore-initial=1116:0 /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.ext2 -
elif [ "{{ FORMAT }}" = ext4 ]; then
  printf '\123\357' | cmp --bytes=2 --ignore-initial=1080:0 /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.ext4 -
  printf '\074\020\000\000\302\042\000\000\153\004\000\000' | cmp --bytes=12 --ignore-initial=1116:0 /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.ext4 -
  [ "$(/sbin/blkid --match-tag UUID --output value /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.ext4)" = "$(uuidgen --sha1 --namespace="$(uuidgen --sha1 --namespace='@dns' --name mister-muffin.de)" --name $SOURCE_DATE_EPOCH)" ]
elif [ "{{ FORMAT }}" = erofs ]; then
  printf "\342\341\365\340" | cmp --bytes=4 --ignore-initial=1024:0 /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.erofs
  [ "$(tail --bytes=+1073 /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.erofs | head --bytes=16 | od -A n -t x1 -v | tr --delete ' ')" = "$(uuidgen --sha1 --namespace="$(uuidgen --sha1 --namespace='@dns' --name mister-muffin.de)" --name $SOURCE_DATE_EPOCH | tr --delete '-')" ]
elif [ "{{ FORMAT }}" = cpio ]; then
  printf "070701" | cmp --bytes=6 - /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.cpio
else
  echo "unknown format: {{ FORMAT }}" >&2
  exit 1
fi

# creating an ext4 image on a 9p filesystem produces different results compared
# to creating it on a tmpfs or ext4 fs because 9p does not support discards and
# even when running with -E nodiscard, the number of written bytes will differ
# https://lore.kernel.org/linux-ext4/171484520952.2626447.2160419274451668597@localhost/T/#t
mv /tmp/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }} ./cache/mmdebstrap-{{ DIST }}-{{ VARIANT }}.{{ FORMAT }}
