name: Release Workflow

on:
  push:
    tags:
      - '*'

permissions:
  contents: write
  packages: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Nix
        uses: cachix/install-nix-action@v31
        with:
          nix_path: nixpkgs=channel:nixos-unstable

      - name: Use Cachix
        uses: cachix/cachix-action@v16
        with:
          name: trevstack
          authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
        
      - name: Build
        run: >
          nix build
          .#trevstack-linux-amd64
          .#trevstack-linux-arm64
          .#trevstack-linux-arm
          .#trevstack-windows-amd64
          .#trevstack-darwin-amd64
          .#trevstack-darwin-arm64

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          files: |-
            result*/bin/*
  
  # https://docs.docker.com/build/ci/github-actions/manage-tags-labels/
  package:
    runs-on: ubuntu-latest
    needs: release # Wait for binary cache to propagate
    steps:
      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          # list of Docker images to use as base name for tags
          images: |
            ${{ github.repository }}
            ghcr.io/${{ github.repository }}
          # generate Docker tags based on the following events/attributes
          tags: |
            type=ref,event=branch
            type=semver,pattern={{version}}

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ vars.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}