#!/usr/bin/env bash
# Build the Kodi update payload Jacktook's own updater consumes.
#
# Layout mirrors what lib/updater.py expects (see UPDATE_HOST there):
# packages/jacktook_version plain-text version string
# packages/jacktook_changelog plain-text changelog
# zips/<id>/<id>-<ver>.zip addon tree, top-level dir MUST be <id>
# zips/<id>/index.json [{"name": "<zip>"}] -- shape of the GitHub
# contents API the downgrade menu used to read
#
# The zip is validated twice by the updater (inside the package, then after
# install), so addon.xml's version and the filename must agree.
set -euo pipefail
cd "$(dirname "$0")"
ID="plugin.video.jacktook"
VER=$(python3 -c "import xml.etree.ElementTree as ET;print(ET.parse('$ID/addon.xml').getroot().attrib['version'])")
OUT="dist"
ZIPDIR="$OUT/zips/$ID"
mkdir -p "$OUT/packages" "$ZIPDIR"
# Stale bytecode must never ship inside the package.
find "$ID" -name __pycache__ -type d -exec rm -rf {} + 2>/dev/null || true
rm -f "$ZIPDIR/$ID-$VER.zip"
zip -qr "$ZIPDIR/$ID-$VER.zip" "$ID" -x '*.pyc' -x '*__pycache__*' -x '*.git*'
printf '%s' "$VER" > "$OUT/packages/jacktook_version"
[ -f CHANGELOG.md ] && cp CHANGELOG.md "$OUT/packages/jacktook_changelog" \
|| printf 'Local build %s\n' "$VER" > "$OUT/packages/jacktook_changelog"
python3 - "$ZIPDIR" <<'PY'
import json, os, sys
d = sys.argv[1]
names = sorted(f for f in os.listdir(d) if f.endswith(".zip"))
json.dump([{"name": n} for n in names], open(os.path.join(d, "index.json"), "w"))
print("index.json ->", names)
PY
echo "built $ID $VER"
ls -la "$ZIPDIR"