name: build & release

on:
  push:
    branches:
      - master
defaults:
  run:
    shell: nu {0}

permissions:
  contents: write

jobs:
  build-release:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.vars.outputs.version }}
      created-tag: ${{ steps.autotag.outputs.created-tag }}
    steps:
    - uses: actions/checkout@v3
    - uses: hustcer/setup-nu@v3.9
    - run: try { git fetch --depth=1 origin +refs/tags/*:refs/tags/* }
    - uses: dtolnay/rust-toolchain@stable

    - name: Vars
      id: vars
      run: |
        $"version=(open ./Cargo.toml | get package.version)(char nl)" out>> $env.GITHUB_OUTPUT

    - name: Output
      env:
        version: ${{ steps.vars.outputs.version }}
      run: |
        print $"Version: ($env.version)"

    - run: cargo build --release

    - name: Autotag
      id: autotag
      env:
        version: ${{ steps.vars.outputs.version }}
      run: |
        let version = $"v($env.version)"
        let untagged = (git tag -l | lines -s | find $version | is-empty)
        if $untagged {
          print $"pushing tag ($version)"

          git config --global user.name 'github-actions[bot]'
          git config --global user.email '88293801+lizclipse@users.noreply.github.com'
          git tag $version
          git push origin $version
        } else {
          print "version already tagged"
        }
        $"created-tag=($untagged)(char nl)" out>> $env.GITHUB_OUTPUT

    - uses: softprops/action-gh-release@v1
      if: ${{ steps.autotag.outputs.created-tag == 'true' }}
      with:
        tag_name: v${{ steps.vars.outputs.version }}
        draft: true

    - name: Crates.io publish
      if: ${{ steps.autotag.outputs.created-tag == 'true' }}
      env:
        CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
      run: cargo publish --verbose --locked
