#!/bin/bash
# Build a self-contained TeX Live tree for the Klammertext SKS "tex"/"pdf"
# targets: scheme-small plus the additional packages the SKS requires, with
# all formats rebuilt.  This is the single source of truth for constructing a
# Klammertext TeX Live directory — used both by the Docker build (Dockerfile,
# per-arch) and for native installs.
#
# Usage:
#   texlive_additional_packages.sh <texdir> [mirror]
#
#   <texdir>   Destination directory for the TeX Live tree (created by
#              install-tl), e.g. /opt/texlive or ~/external/texlive/2026.
#              Should not already exist.
#   [mirror]   A CONCRETE tlnet mirror URL.  Must NOT be the mirror.ctan.org
#              redirect: it resolves to a different mirror (possibly a different
#              TeX Live revision) on each call, which makes tlmgr abort partway
#              with "tlmgr itself needs to be updated".  Defaults to a pinned
#              CTAN mirror.  Once the current TeX Live year is frozen (the next
#              release ships), point this at the historic tlnet-final snapshot
#              for exact reproducibility, e.g.
#                https://ftp.math.utah.edu/pub/texlive/historic/2026/tlnet-final
#
# install-tl fetches the binaries for the ARCHITECTURE it runs on, so running
# this under arm64 produces an arm64 tree and under x86_64 an x86_64 tree.
#
# Prerequisites on the host: perl, tar, gzip, xz (xz-utils), and either wget or
# curl (macOS ships curl, not wget).  fontconfig is recommended so fmtutil can
# build all formats cleanly.

set -eux

TEXDIR="${1:?usage: $0 <texdir> [mirror]}"
MIRROR="${2:-https://ctan.math.illinois.edu/systems/texlive/tlnet}"

# --- Fetch the installer into a scratch dir --------------------------------
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
cd "$WORK"
# Fetch the installer with whichever downloader is present (macOS has curl, not
# wget; Debian build images have wget).
if command -v wget >/dev/null 2>&1; then
    wget -q "$MIRROR/install-tl-unx.tar.gz"
else
    curl -fsSL -O "$MIRROR/install-tl-unx.tar.gz"
fi
tar --strip-components=1 -xzf install-tl-unx.tar.gz

# --- Base install: scheme-small into $TEXDIR -------------------------------
cat > texlive.profile <<PROFILE
selected_scheme scheme-small
TEXDIR $TEXDIR
TEXMFLOCAL $TEXDIR/texmf-local
TEXMFSYSCONFIG $TEXDIR/texmf-config
TEXMFSYSVAR $TEXDIR/texmf-var
tlpdbopt_install_docfiles 0
tlpdbopt_install_srcfiles 0
tlpdbopt_autobackup 0
PROFILE

# install-tl's in-line fmtutil can exit 3 before all packages are present;
# that is non-fatal (install-tl continues) and the formats are rebuilt below.
./install-tl --profile=texlive.profile --repository="$MIRROR"

# --- Use the tlmgr from the tree we just built (absolute path), not whatever
#     tlmgr may be on PATH.  Pin its repo to the same concrete mirror and sync
#     it to that repo's revision before installing more packages. -----------
ARCH="$(ls "$TEXDIR/bin")"
TLMGR="$TEXDIR/bin/$ARCH/tlmgr"
"$TLMGR" option repository "$MIRROR"
"$TLMGR" update --self

# --- Additional packages required by the SKS beyond scheme-small -----------
# Single list, used both for the install and for the provenance README below,
# so the two cannot drift apart.
PACKAGES="adjustbox collectbox collection-fontsrecommended enumitem fontaxes \
footmisc inconsolata layouts mdframed multirow needspace opensans pict2e \
textpos titlesec upquote zref"

# shellcheck disable=SC2086  # intentional word splitting into separate args
"$TLMGR" install $PACKAGES

# --- Rebuild every format now that the full package set is installed -------
"$TEXDIR/bin/$ARCH/fmtutil-sys" --all

# --- Provenance: record how this tree was constructed ----------------------
# Written into the tree itself so it is self-documenting when found later.
RELEASE="$(head -n1 "$TEXDIR/release-texlive.txt" 2>/dev/null || echo unknown)"
BUILT="$(date -u '+%Y-%m-%d %H:%M:%S UTC')"
cat > "$TEXDIR/KLAMMERTEXT_BUILD_INFO.txt" <<INFO
Klammertext TeX Live tree
=========================

Built for the Klammertext Standard Klammer Set (SKS) "tex"/"pdf" targets by
doc/install/texlive_additional_packages.sh.

Built:         $BUILT
Mirror:        $MIRROR
TeX Live:      $RELEASE
Architecture:  bin/$ARCH
Base scheme:   scheme-small
Docfiles/srcfiles omitted; all formats rebuilt with fmtutil-sys --all.

Additional packages installed beyond scheme-small:
$(printf '  %s\n' $PACKAGES)

Reconstruct an equivalent tree with:
  texlive_additional_packages.sh <texdir> $MIRROR

Note: the mirror above serves the CURRENT TeX Live release, which receives
package updates within its year, so a rebuild is not guaranteed byte-identical.
For exact reproducibility, rebuild from the frozen historic tlnet-final
snapshot once the release year is no longer current, e.g.
  https://ftp.math.utah.edu/pub/texlive/historic/<year>/tlnet-final
INFO

echo "Klammertext TeX Live tree built in $TEXDIR (binaries in bin/$ARCH)"
echo "Provenance written to $TEXDIR/KLAMMERTEXT_BUILD_INFO.txt"
