name: release

on:
  push:
    tags:
      - 'v*'

jobs:
  create-release:
    name: Create Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout source code
        uses: actions/checkout@v2

      - name: Create Release Notes
        uses: actions/github-script@v5
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            await github.request(`POST /repos/${{ github.repository }}/releases`, {
              tag_name: "${{ github.ref }}",
              generate_release_notes: true
            });

  build-artifacts:
    name: 'Build artifacts for ${{ matrix.os }}'
    runs-on: ${{ matrix.os }}
    needs: create-release
    strategy:
      matrix:
        name:
          - linux
          - macos
          - windows
        include:
          - name: linux
            os: ubuntu-latest
            artifact_name: 'http-server-linux'
            asset_name: 'http-server'
            asset_extension: '.tar.gz'

          - name: macos
            os: macos-latest
            artifact_name: 'http-server-macos'
            asset_name: 'http-server'
            asset_extension: '.tar.gz'

          - name: windows
            os: windows-latest
            artifact_name: 'http-server-windows.exe'
            asset_name: 'http-server.exe'
            asset_extension: '.zip'
    steps:
      - name: Checkout source code
        uses: actions/checkout@v2

      - name: Setup environment variables
        shell: bash
        run: |
          RELEASE_VERSION=$(echo ${GITHUB_REF:10}) >> $GITHUB_ENV

      - name: Setup Rust Toolchain
        uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: stable

      - name: Build optimized executable
        run: cargo build --release --locked

      - name: Archive release assets
        shell: bash
        run: |
          if [ "${{ matrix.os }}" = "windows-latest" ]; then
            cp target/release/http-server.exe ${{ matrix.asset_name }}
          else
            cp target/release/http-server "${{ matrix.asset_name }}"
          fi

      - name: Attach builded binaries to release
        uses: svenstaro/upload-release-action@v1-release
        with:
          asset_name: 'http-server_${{ matrix.os }}'
          file: '${{ matrix.asset_name }}'
          repo_token: ${{ secrets.GITHUB_TOKEN }}
          tag: ${{ github.ref }}

  publish-crate:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    needs: build-artifacts
    steps:
      - name: Checkout source code
        uses: actions/checkout@v2

      - uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: stable

      - run: cargo login ${CRATES_IO_TOKEN}
        env:
          CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}

      - name: publish crate
        run: cargo publish
