#!/usr/bin/env bash
# Build per-addon zip artefacts from HEAD via git-archive.
#
# - Discovers top-level addon folders (Foo/Foo.toc).
# - Re-creates dist/ each run.
# - Always archives HEAD, so the working tree state is irrelevant.
# - If more than one addon folder is present, also emits <repo>-all.zip
#   with every addon folder side-by-side at the zip root.
# - When run inside Gitea Actions the working tree lives under a
#   per-job dir like /var/lib/act_runner/work/.../hostexecutor, so the
#   repo name comes from $GITHUB_REPOSITORY (set by the runner) and
#   only falls back to the toplevel basename for local invocations.
set -euo pipefail

root=$(git rev-parse --show-toplevel)
cd "$root"

# Gitea Actions sets GITHUB_REPOSITORY=owner/repo. The basename of
# `git rev-parse --show-toplevel` inside the runner is the worker dir
# (e.g. `hostexecutor`), which would name the bundle wrong.
if [ -n "${GITHUB_REPOSITORY:-}" ]; then
    repo_name="${GITHUB_REPOSITORY##*/}"
else
    repo_name=$(basename "$root")
fi
dist="$root/dist"

# Find Foo/Foo.toc pairs at depth 1; ignore libs nested deeper.
addons=()
while IFS= read -r toc; do
    dir=$(dirname "$toc")
    folder=$(basename "$dir")
    base=$(basename "$toc" .toc)
    # Accept Foo.toc and Foo_Wrath.toc style flavour variants; folder must match
    # at least one toc basename prefix (Foo).
    case "$base" in
        "$folder"|"$folder"_*) addons+=("$folder") ;;
    esac
done < <(command find . -mindepth 2 -maxdepth 2 -type f -name '*.toc' | sed 's|^\./||' | sort)

# Dedupe (a folder with Foo.toc + Foo_Wrath.toc shows up twice).
if [ ${#addons[@]} -gt 0 ]; then
    mapfile -t addons < <(printf '%s\n' "${addons[@]}" | awk '!seen[$0]++')
fi

if [ ${#addons[@]} -eq 0 ]; then
    echo "no addon folders found (looking for */Foo.toc with matching folder name)" >&2
    exit 1
fi

rm -rf "$dist"
mkdir -p "$dist"

for folder in "${addons[@]}"; do
    out="$dist/$folder.zip"
    # No --prefix: the folder already sits at the repo root, so git-archive
    # emits entries as <folder>/... which is exactly what
    # Interface/AddOns/ expects after extraction.
    git archive HEAD --format=zip -o "$out" -- "$folder"
    echo "built dist/$folder.zip"
done

# Combined bundle only makes sense when there are multiple addons.
if [ ${#addons[@]} -gt 1 ]; then
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    git archive HEAD --format=tar -- "${addons[@]}" | tar -x -C "$tmp"
    out="$dist/$repo_name-all.zip"
    ( cd "$tmp" && zip -qr "$out" "${addons[@]}" )
    echo "built dist/$repo_name-all.zip"
fi
