# Build and release tola binaries for all platforms
# Triggered on version tags (v*)
name: Release

on:
  push:
    tags:
      - 'v*'

permissions:
  contents: write

jobs:
  build:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v4

      # Install Nix and configure Cachix for binary caching
      - uses: cachix/install-nix-action@v30
        with:
          nix_path: nixpkgs=channel:nixos-unstable

      - uses: cachix/cachix-action@v15
        with:
          name: tola
          signingKey: '${{ secrets.CACHIX_SIGNING_KEY }}'
          authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'

      # Build Linux/macOS targets - logs are captured by Cachix for upload
      - name: Build and push to Cachix (Linux/macOS)
        run: |
          set -e
          mkdir -p artifacts

          for target in x86_64-linux x86_64-linux-static aarch64-linux aarch64-linux-static aarch64-darwin; do
            echo "Building $target..."
            outpath=$(nix build -j auto --no-link --print-out-paths ./#$target)
            tar -czvf "artifacts/tola-$target.tar.gz" -C "$outpath/bin" tola
          done

      # Build Windows separately - silence logs to skip Cachix upload
      - name: Build Windows (no Cachix)
        run: |
          set -e
          echo "Building x86_64-windows..."
          outpath=$(nix build -j auto --no-link --print-out-paths ./#x86_64-windows 2>/dev/null)
          (cd "$outpath/bin" && zip -9 "$OLDPWD/artifacts/tola-x86_64-windows.zip" tola.exe)

          ls -la artifacts/

      # Upload all artifacts to GitHub Release
      - name: Create Release
        run: |
          # Use commit message as release notes
          git log -1 --format="%B" > notes.md

          # Delete existing release if it exists, then create new one
          gh release delete ${{ github.ref_name }} --yes || true
          gh release create ${{ github.ref_name }} artifacts/* --notes-file notes.md
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
