name: Build and Publish Arch Package
on:
  push:
    tags:
      - 'v*'

jobs:
  build-arch:
    runs-on:
      - ubuntu-24.04
    strategy:
      matrix:
        include:
          - goarch: amd64
            pkgarch: x86_64
          - goarch: arm64
            pkgarch: aarch64
    steps:
      - name: Install build dependencies
        run: sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends zstd curl

      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version-file: src/go.mod

      - name: Build binary
        run: |
          cd src
          GOARCH=${{ matrix.goarch }} GOOS=linux GOTOOLCHAIN=auto \
            go build -ldflags="-s -w" -trimpath -o axolotl .

      - name: Create package
        run: |
          pkgver=$(echo "${{ github.ref_name }}" | sed 's/^v//')
          pkgname="axolotl"
          pkgrel=1
          pkgarch="${{ matrix.pkgarch }}"

          pkgdir=$(mktemp -d)/pkg
          mkdir -p "$pkgdir/usr/bin"
          install -Dm755 src/axolotl "$pkgdir/usr/bin/axolotl"
          ln -s axolotl "$pkgdir/usr/bin/ax"

          size=$(du -sb "$pkgdir/usr" | awk '{print $1}')
          cat > "$pkgdir/.PKGINFO" <<EOF
          pkgname = $pkgname
          pkgver = $pkgver-$pkgrel
          pkgdesc = CLI-native issue tracker using SQLite
          url = https://g.eliaskohout.de/eliaskohout/axolotl
          builddate = $(date +%s)
          packager = Gitea Actions
          size = $size
          arch = $pkgarch
          license = MIT
          EOF

          pkg_file="$PWD/${pkgname}-${pkgver}-${pkgrel}-${pkgarch}.pkg.tar.zst"
          tar -C "$pkgdir" -c --zstd -f "$pkg_file" .
          echo "PKG_FILE=$pkg_file" >> "$GITHUB_ENV"

      - name: Publish to Gitea Registry
        run: |
          curl --fail-with-body \
            --user "${{ github.repository_owner }}:${{ secrets.ACCESS_TOKEN }}" \
            --upload-file "$PKG_FILE" \
            "${{ github.server_url }}/api/packages/${{ github.repository_owner }}/arch/push"
