on:
  release:
    types: [created]

name: Release

defaults:
  run:
    shell: bash

jobs:
  build-release-binaries:
    name: Build binaries for release
    continue-on-error: true

    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]

    runs-on: "${{ matrix.os }}"
    steps:
      - uses: actions/checkout@v2
      - uses: actions/cache@v2
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
      - name: build
        run: RUSTFLAGS='-C link-arg=-s' cargo build --release
      - name: identify the artifact and name it per the os
        run: |
          set -e -x
          bin=target/release/calc
          archive="$(printf 'calc-%s.tar.bz2' "$(uname | tr '[:upper:]' '[:lower:]')")"
          if [ ! -f "$bin" ]; then
            bin="$bin.exe"
          fi
          if [ ! -f "$bin" ]; then
            echo "could not locate compiled executable"
            exit 1
          fi
          mv "$bin" .
          bin="$(basename "$bin")"
          file "$bin"

          if [[ "$archive" == *mingw* ]]; then
            # in this case, the file doesn't end with .exe, but we're still building for windows
            # let's fix that
            mv "$bin" "$bin.exe"
            bin="$bin.exe"
            archive=calc-win.tar.bz2
          fi

          tar -cvjf "$archive" "$bin"
          echo "artifact=$archive" >> "$GITHUB_ENV"

          ls -lh "$bin" "$archive"
      - uses: actions/upload-artifact@v2
        with:
          name: "${{ env.artifact }}"
          path: "${{ env.artifact }}"

  upload-release-binaries:
    name: Add binaries to release
    if: always()
    needs: build-release-binaries
    continue-on-error: true

    strategy:
      matrix:
        artifact: [calc-linux.tar.bz2, calc-darwin.tar.bz2, calc-win.tar.bz2]

    runs-on: ubuntu-latest

    steps:
      - uses: actions/download-artifact@v2
        with:
          name: "${{ matrix.artifact }}"
      - name: Add to release
        uses: skx/github-action-publish-binaries@master
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          args: "${{ matrix.artifact }}"
