# Git(tea) Actions workflow: Build and publish standalone binaries **plus** bundled `static/` assets
# ────────────────────────────────────────────────────────────────────
#  ✧  Builds the Go‑based WoL server for four targets **and** packt das Verzeichnis
#      `static` zusammen mit der Binary, sodass es relativ zur ausführbaren Datei
#      liegt (wichtig für die eingebauten Bootstrap‑Assets & favicon).
#
#       • linux/amd64    → wol-server-linux-amd64.tar.gz
#       • linux/arm64    → wol-server-linux-arm64.tar.gz
#       • linux/arm/v7   → wol-server-linux-armv7.tar.gz
#       • windows/amd64  → wol-server-windows-amd64.zip
#
#  ✧  Artefakte landen im Workflow und – bei Tag‑Push (vX.Y.Z) – als Release‑Assets.
#
#  Secrets/variables:
#    GITEA_TOKEN – optional, falls default token keine Release‑Rechte hat.
# ────────────────────────────────────────────────────────────────────

name: build-binaries

on:
  push:
    branches: [ "main" ]
    tags:     [ "v*" ]

jobs:
  build:
    if: startsWith(github.ref, 'refs/tags/')
    runs-on: ubuntu-fast

    strategy:
      matrix:
        include:
          - goos: windows
            goarch: amd64
            ext: ".exe"

    env:
      GO_VERSION: "1.25"
      BINARY_NAME: duidreader

    steps:
      - name: Checkout source
        uses: actions/checkout@v3

      - name: Set up Go ${{ env.GO_VERSION }}
        uses: actions/setup-go@v4
        with:
          go-version: ${{ env.GO_VERSION }}
          cache: true

      - name: Build ${{ matrix.goos }}/${{ matrix.goarch }}${{ matrix.goarm && format('/v{0}', matrix.goarm) || '' }}
        shell: bash
        run: |
          set -e
          mkdir -p dist/package
          if [ -n "${{ matrix.goarm }}" ]; then export GOARM=${{ matrix.goarm }}; fi
          CGO_ENABLED=0 GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -trimpath -ldflags "-s -w" \
            -o "dist/package/${BINARY_NAME}${{ matrix.ext }}" .
          # Assets: statisches Verzeichnis beilegen
          # cp -r static dist/package/

      - name: Package archive with static assets
        shell: bash
        run: |
          set -e
          cd dist
          if [ "${{ matrix.goos }}" == "windows" ]; then
            ZIP_NAME="${BINARY_NAME}-windows-amd64.zip"
            (cd package && zip -r "../$ZIP_NAME" .)
          else
            ARCH_SUFFIX="${{ matrix.goarch }}"
            if [ "${{ matrix.goarch }}" == "arm" ]; then ARCH_SUFFIX="armv${{ matrix.goarm }}"; fi
            TAR_NAME="${BINARY_NAME}-${{ matrix.goos }}-${ARCH_SUFFIX}.tar.gz"
            tar -czf "$TAR_NAME" -C package .
          fi

      - name: Upload workflow artifact
        uses: actions/upload-artifact@v3
        with:
          name: ${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.goarm && format('v{0}', matrix.goarm) || '' }}
          path: dist/*.tar.gz
          if-no-files-found: ignore
      - uses: actions/upload-artifact@v3
        with:
          name: windows-amd64
          path: dist/*.zip
          if-no-files-found: ignore

  # Release Schritt für Tag‑Pushes
  release:
    if: startsWith(github.ref, 'refs/tags/')
    needs: build
    runs-on: ubuntu-fast
    permissions:
      contents: write

    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v3
        with:
          path: ./dist

      - name: Create / Update release
        uses: softprops/action-gh-release@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
        with:
          name: "Release ${{ github.ref_name }}"
          tag_name: ${{ github.ref_name }}
          draft: false
          prerelease: false
          files: |
            dist/**/duidreader-*.tar.gz
            dist/**/duidreader-*.zip
  publish-agent:
    if: startsWith(github.ref, 'refs/tags/')
    needs: release
    runs-on: ubuntu-fast
    env:
      PRODUCT: duidreader
      AGENT_URL: ${{ secrets.AGENT_URL }}
      AGENT_TOKEN: ${{ secrets.AGENT_TOKEN }}

      # Funktioniert in GitHub und Gitea (Actions) weitgehend gleich:
      SERVER_URL: ${{ github.server_url }}       # z.B. https://github.com oder https://gitea.example.com
      REPOSITORY: ${{ github.repository }}       # owner/repo
      TAG: ${{ github.ref_name }}                # vX.Y.Z

    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v3
        with:
          path: ./dist

      - name: Publish release metadata to Version Agent
        shell: bash
        run: |
          set -euo pipefail

          if [[ -z "${AGENT_URL:-}" || -z "${AGENT_TOKEN:-}" ]]; then
            echo "Missing AGENT_URL or AGENT_TOKEN" >&2; exit 1
          fi

          VERSION="${TAG#v}"                     # 12.3.1[-rc.1|-beta.1]
          MAJOR="${VERSION%%.*}"                 # 12
          BRANCH="${MAJOR}.x"                    # 12.x

          CHANNEL="stable"
          [[ "$VERSION" == *"-rc"* ]] && CHANNEL="rc"
          [[ "$VERSION" == *"-beta"* ]] && CHANNEL="beta"
          # Optional: Nightly-Channel bei Non-Tag-Builds (separater Job, siehe unten)

          RELEASED_AT="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
          NOTES_URL="${SERVER_URL}/${REPOSITORY}/releases/tag/${TAG}"

          publish() { # args: OS ARCH FILE
            local OS="$1" ARCH="$2" FILE="$3"
            local BIT="64"
            case "$ARCH" in 386|armv7) BIT="32";; esac

            local FNAME="$(basename "$FILE")"
            local URL="${SERVER_URL}/${REPOSITORY}/releases/download/${TAG}/${FNAME}"

            local SHA256 SIZE
            SHA256="$(sha256sum "$FILE" | awk '{print $1}')"
            SIZE="$(stat -c%s "$FILE")"

            jq -n \
              --arg branch "$BRANCH" \
              --arg channel "$CHANNEL" \
              --arg arch "$ARCH" \
              --arg bit "$BIT" \
              --arg os "$OS" \
              --arg version "$VERSION" \
              --arg released_at "$RELEASED_AT" \
              --arg notes "$NOTES_URL" \
              --arg url "$URL" \
              --arg sha256 "$SHA256" \
              --argjson size "$SIZE" \
              '{
                branch:$branch, channel:$channel, arch:$arch, bit:$bit, os:$os,
                release:{
                  version:$version, released_at:$released_at, notes_url:$notes,
                  assets:[{url:$url, sha256:$sha256, size_bytes:$size}]
                }
              }' > payload.json
            echo @payload.json
            curl -fsS -H "Content-Type: application/json" \
                 -H "Authorization: Bearer ${AGENT_TOKEN}" \
                 -d @payload.json "${AGENT_URL}/v1/publish"
          }

          shopt -s nullglob

          # linux/amd64
          # for f in dist/**/${PRODUCT}-linux-amd64.tar.gz;  do publish linux   amd64 "$f"; done
          # linux/arm64
          # for f in dist/**/${PRODUCT}-linux-arm64.tar.gz;  do publish linux   arm64 "$f"; done
          # linux/armv7
          # for f in dist/**/${PRODUCT}-linux-armv7.tar.gz;  do publish linux   armv7 "$f"; done
          # windows/amd64
          for f in dist/**/${PRODUCT}-windows-amd64.zip;   do publish windows amd64 "$f"; done