name: TubeArchivistMetadata Release

on:
  push:
    tags:
      - v*

jobs:
  build:
    runs-on: ubuntu-latest
    name: Build & Release
    permissions:
      contents: write
      packages: read

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: master
          fetch-depth: 0

      - name: Get release version
        id: newtag
        uses: "WyriHaximus/github-action-get-previous-tag@v1"

      - name: Setup .Net
        uses: actions/setup-dotnet@v1
        with:
          dotnet-version: 8.0.x

      - name: Add Jellyfin GitHub Nuget registry to sources
        run: |
          dotnet nuget add source \
            --username DarkFighterLuke \
            --password ${{ secrets.GITHUB_TOKEN }} \
            --store-password-in-clear-text \
            --name github https://nuget.pkg.github.com/jellyfin/index.json

      - name: Get version number only
        run: |
          TAG=${{ steps.newtag.outputs.tag }}
          echo "VERSION=${TAG#v}" >> $GITHUB_ENV

      - name: Generate release message
        run: |
          # Read the YAML file and extract the value of the 'changelog' field
          changelog=$(awk '/changelog:/ {flag=1; next} /^[^ ]/ {flag=0} flag' build.yaml | awk '{$1=$1};1')

          # Check if changelog contains multiple lines
          if [[ $(echo "$changelog" | wc -l) -gt 1 ]]; then
              changelog=$(echo "$changelog" | sed 's/^/* /')
          else
              changelog="* $changelog"
          fi

          # Create release-changelog.md
          echo "Changelog:" > release-changelog.md
          echo "$changelog" >> release-changelog.md


      - name: Build Jellyfin Plugin
        uses: DarkFighterLuke/jellyfin-plugin-repository-manager@7a96768accc155ac7b597351b5033532f3c48173
        id: jprm
        with:
          dotnet-target: net8.0
          version: ${VERSION}
          update-manifest: "true"

      - name: Create release
        uses: ncipollo/release-action@v1
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          artifacts: ${{ steps.jprm.outputs.artifact }}
          makeLatest: latest
          bodyFile: release-changelog.md
          tag: ${{ steps.newtag.outputs.tag }}
          allowUpdates: true

      - name: Commit manifest.json
        uses: EndBug/add-and-commit@v9
        with:
          add: manifest.json
          commit: --signoff
          message: "Update manifest.json"
          pull: "--no-rebase -X ours origin master"
