#!/bin/sh
# tenkana, a spider that jumps from the checkpoints of your TeX document.
# Copyright © 2026 निरंजन (Niranjan)
#
# tenkana is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# tenkana is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with tenkana.  If not, see <https://www.gnu.org/licenses/>.
#
# tenkana was written by Claude, a large language model (LLM) made by
# Anthropic.  Courts are divided on whether material generated by an LLM can be
# protected by copyright.  Should it be found that the copyright claimant
# cannot hold copyright in any part of tenkana, that part is in the public
# domain.  Wherever copyright does hold, tenkana is distributed under the terms
# of the GNU General Public License, version 3 or (at your option) any later
# version, as stated above.

# Build tenkana: make the single-file `tenkana' command, tenkana.pyz.
#
#   ./build.sh          writes tenkana.pyz next to this script
#   ./build.sh PATH     writes it to PATH instead (a file, or a folder to
#                       put tenkana.pyz in; missing folders are made)
#   ./build.sh clean    removes what building made: build/ and tenkana.pyz
#
# The work is done in build/, next to this script, which is emptied first;
# the finished file is checked (it must run and report this version) before
# it is copied out, and build/ is then removed.  If the check fails, build/
# is kept, to look at.  Like build/, tenkana.pyz is generated and is not kept
# in git or in the CTAN package.
#
# tenkana.pyz is a zip of src/tenkana, started by src/pyzmain.py, that
# runs with `/usr/bin/env python3'.  It is the same byte for byte whatever
# Python 3.9 or newer builds it: the files are stored uncompressed, in a
# fixed order, with a fixed date.
set -e
here=$(cd "$(dirname "$0")" && pwd)
build="$here/build"

case "$1" in
  clean)
    rm -rf "$build" "$here/tenkana.pyz"
    exit 0 ;;
  "") out="$here/tenkana.pyz" ;;
  */) out="${1}tenkana.pyz" ;;
  *) out=$1
     if [ -d "$out" ]; then out="$out/tenkana.pyz"; fi ;;
esac
if [ $# -gt 1 ]; then
  echo "usage: ./build.sh [PATH | clean]" >&2
  exit 2
fi

python3 -c 'import sys; sys.exit(sys.version_info < (3, 9))' \
  2>/dev/null || {
  echo "build.sh: needs Python 3.9 or newer (python3 on your PATH)." >&2
  exit 1
}

rm -rf "$build"
mkdir "$build"
python3 -B - "$here/src" "$build/tenkana.pyz" <<'EOF'
import hashlib, os, sys, zipfile
top, out = sys.argv[1:]
src = os.path.join(top, "tenkana")
DATE = (1980, 1, 1, 0, 0, 0)  # the earliest date a zip file can hold
names = sorted(n for n in os.listdir(src)
               if n.endswith((".py", ".c")))
files = {}
for n in names:
    with open(os.path.join(src, n), "rb") as g:
        files[n] = g.read()
# the hash names tenkana's unpacked copy in the user's cache (pyzmain.py)
h = hashlib.sha256()
for n in names:
    h.update(n.encode() + b"\0" + files[n] + b"\0")
with open(os.path.join(top, "pyzmain.py"), "rb") as g:
    main = g.read().replace(b"@KEY@", h.hexdigest()[:16].encode())
with open(out, "wb") as f:
    f.write(b"#!/usr/bin/env python3\n")
    with zipfile.ZipFile(f, "w", zipfile.ZIP_STORED) as z:
        def add(name, data):
            info = zipfile.ZipInfo(name, DATE)
            info.external_attr = 0o644 << 16
            z.writestr(info, data)
        add("__main__.py", main)
        for n in names:
            add("tenkana/" + n, files[n])
os.chmod(out, 0o755)
EOF

# the file must run and be this version
version=$(python3 -B -c 'import sys; sys.path.insert(0, sys.argv[1])
from tenkana import __version__; print(__version__)' "$here/src")
# (with a cache of its own in build/, so the user's cache is not touched
# and unpacking is tried too)
first=$(XDG_CACHE_HOME="$build/cache" python3 "$build/tenkana.pyz" --version |
  sed -n 1p)
[ "$first" = "tenkana $version" ] || {
  echo "build.sh: the built file does not run correctly; see above." >&2
  exit 1
}

mkdir -p "$(dirname "$out")"
cp "$build/tenkana.pyz" "$out.tmp"
mv -f "$out.tmp" "$out"
rm -rf "$build"
echo "build.sh: wrote $out (tenkana $version)"
