#!/bin/bash

# XXX: this should be re-written to be part of our installer, possibly
# as a submodule of tsa-misc, but maybe not in fabric

set -e

# bash-specific
set -o pipefail

# the parameters for the image

# where to fetch the packages from
MIRROR="https://deb.debian.org/debian"

# this will really always be "debian", but might tolerate "ubuntu" if
# you (a) change the mirror above, (b) the suite, (c) the variant,
# and, more importantly, if mmdebootstrap supports it
IMAGE=debian
SUITE=bullseye
VARIANT=minbase
RUNTIME=podman

# No servicable parts below this line
MODE=fakeroot
TAG=$SUITE-$VARIANT

# fetch the last update time of the mirror to create a reproducible
# tarball based on that date
MIRROR_DATE=$(curl -s $MIRROR/dists/$SUITE/Release | grep-dctrl -s Date -n '')
echo "I: mirror $MIRROR timestamp is $MIRROR_DATE" >&2
# to have this reproducible
SOURCE_DATE_EPOCH=$(date --date="$MIRROR_DATE" +%s)
export SOURCE_DATE_EPOCH
echo "I: epoch is $SOURCE_DATE_EPOCH seconds" >&2

# this creates an image similar to the official ones built by
# debuerreotype, except that instead of needing a whole set of scripts
# and hacks, we only rely on mmdebstrap.
#
# the downside is that the image is not reproducible (even if ran
# against the same mirror without change), mainly because `docker
# import` stores the import timestamp inside the image. however, the
# internal checksum itself should be reproducible.
mmdebstrap \
  --mode=$MODE \
  --variant=$VARIANT \
  --aptopt='Acquire::Languages "none"' \
  --dpkgopt='path-exclude=/usr/share/man/*' \
  --dpkgopt='path-exclude=/usr/share/man/man[1-9]/*' \
  --dpkgopt='path-exclude=/usr/share/locale/*' \
  --dpkgopt='path-include=/usr/share/locale/locale.alias' \
  --dpkgopt='path-exclude=/usr/share/lintian/*' \
  --dpkgopt='path-exclude=/usr/share/info/*' \
  --dpkgopt='path-exclude=/usr/share/doc/*' \
  --dpkgopt='path-include=/usr/share/doc/*/copyright' \
  --dpkgopt='path-exclude=/usr/share/{doc,info,man,omf,help,gnome/help,examples}/*' \
  $SUITE \
  - \
  $MIRROR |
    $RUNTIME import -c 'CMD ["bash"]' - $IMAGE:$TAG

# note that we could also have used `| tar --delete /$PATH` to exclude files
