name: Export source archive

on:
  workflow_dispatch:

jobs:
  export-source:
    name: Create source tar.gz
    runs-on: ubuntu-latest

    steps:
      - name: Check out selected revision
        uses: actions/checkout@v4
        with:
          fetch-depth: 1
          persist-credentials: false

      - name: Create source archive
        shell: bash
        run: |
          set -euo pipefail

          commit="$(git rev-parse HEAD)"
          short_sha="$(git rev-parse --short=12 HEAD)"

          remote_url="$(git config --get remote.origin.url || true)"
          repo_name="${remote_url##*/}"
          repo_name="${repo_name%.git}"

          if [[ -z "${repo_name}" || "${repo_name}" == "." ]]; then
            repo_name="$(basename "$(git rev-parse --show-toplevel)")"
          fi

          # Produce a filesystem-safe, predictable archive name.
          repo_slug="$(
            printf '%s' "${repo_name}" |
              tr '[:upper:]' '[:lower:]' |
              sed -E 's/[^a-z0-9._-]+/-/g; s/^-+//; s/-+$//'
          )"

          if [[ -z "${repo_slug}" ]]; then
            repo_slug="source"
          fi

          archive_root="${repo_slug}-${short_sha}"
          output_dir="${PWD}/artifacts"
          archive_path="${output_dir}/${archive_root}.tar.gz"

          mkdir -p "${output_dir}"

          # Archive tracked files only. Git metadata is intentionally excluded.
          git archive \
            --format=tar \
            --prefix="${archive_root}/" \
            HEAD | gzip -9 > "${archive_path}"

          (
            cd "${output_dir}"
            sha256sum "${archive_root}.tar.gz" > "${archive_root}.tar.gz.sha256"
          )

          echo "Created source archive for ${repo_name} at commit ${commit}:"
          ls -lh "${output_dir}"

      - name: Upload source archive
        uses: actions/upload-artifact@v4
        with:
          name: source-archive
          path: artifacts/
          if-no-files-found: error
          compression-level: 0
          retention-days: 30
