name: Publish Nuget packages

on:
  workflow_dispatch:
  push:
    branches:
      - master

jobs:
  version:
    runs-on: ubuntu-latest
    outputs:
      version-number: ${{ steps.get-version.outputs.version-number }}
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Get Version String
        id: get-version
        shell: pwsh
        run: |
          $MidnightUtc = [DateTime]::UtcNow.Date
          $BranchName = "${{ github.ref_name }}".replace('/','-').replace('.','-')
          $ApiVersion = (Select-Xml -Path 'src/Artemis.Core/Artemis.Core.csproj' -XPath '//PluginApiVersion').Node.InnerText
          $NumberOfCommitsToday = (git log --after=$($MidnightUtc.ToString("o")) --oneline | Measure-Object -Line).Lines
          $VersionNumber = "$ApiVersion.$($MidnightUtc.ToString("yyyy.MMdd")).$NumberOfCommitsToday"
          # If we're not in master, add the branch name to the version so it counts as prerelease 
          if ($BranchName -ne "master") { $VersionNumber += "-$BranchName" }
          "version-number=$VersionNumber" >> $Env:GITHUB_OUTPUT

  nuget:
    name: Publish Nuget Packages
    needs: version
    runs-on: ubuntu-latest
    steps:
      - name: Setup .NET
        uses: actions/setup-dotnet@v2
        with:
          dotnet-version: '7.0.x'
      - name: Checkout
        uses: actions/checkout@v3
      - name: Pack Artemis.Core
        run: dotnet pack -c Release -p:Version=${{ needs.version.outputs.version-number }} -p:BuildingNuget=True src/Artemis.Core/Artemis.Core.csproj
      - name: Pack Artemis.UI.Shared
        run: dotnet pack -c Release -p:Version=${{ needs.version.outputs.version-number }} src/Artemis.UI.Shared/Artemis.UI.Shared.csproj
      - name: Push Nugets
        run: dotnet nuget push **/*.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
