name: Release Build and Publish

on:
  release:
    types: [published]

permissions:
  contents: write

jobs:
  build-staging:
    name: Release Build against Staging Dalamud and deploy to MyDalamudPlugins
    runs-on: windows-2022

    # Define the plugin name and Dalamud version variables for this job
    env:
      PLUGIN_NAME: CBT
      DALAMUD_VERSION_NAME: "Staging"
      DALAMUD_VERSION_URL: "https://goatcorp.github.io/dalamud-distrib/stg/latest.zip"

    steps:
      # Checkout the repository code
      - name: Checkout and Initialise
        uses: actions/checkout@v4

      # Install the required .NET SDK
      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '9.x.x'

      # Cache the nuget packages
      - name: Cache Dependencies
        id: cache-dependencies
        uses: actions/cache@v4
        with:
          path: |
            ~/.nuget/packages
          key: ${{ runner.os }}-nuget-${{ hashFiles('**/${{ env.PLUGIN_NAME }}.csproj') }}
          restore-keys: |
            ${{ runner.os }}-nuget-

      # Create the required directory structure and download/extract Dalamud.
      - name: Download and extract Dalamud (${{ env.DALAMUD_VERSION_NAME }})
        run: |
          mkdir -p "$env:AppData\XIVLauncher\addon\Hooks\dev"
          Invoke-WebRequest -Uri "${{ env.DALAMUD_VERSION_URL }}" -OutFile "dalamud.zip"
          Expand-Archive -Path "dalamud.zip" -DestinationPath "$env:AppData\XIVLauncher\addon\Hooks\dev" -Force

      # Restore, build, and test.
      - name: Build Release (${{ env.DALAMUD_VERSION_NAME }})
        id: build_step
        run: |
          dotnet restore `
            && dotnet build --no-restore --configuration Release `
            && dotnet test --no-build --configuration Release

      - name: Prepare zip file
        run: |
          mkdir output
          Copy-Item "${{ env.PLUGIN_NAME }}/bin/Release/${{ env.PLUGIN_NAME }}.json" -Destination output/${{ env.PLUGIN_NAME }}.json -Force
          Compress-Archive -Path ${{ env.PLUGIN_NAME }}/bin/Release/* -DestinationPath output/latest.zip

      - name: Upload zip to GitHub release
        uses: softprops/action-gh-release@v1
        with:
          files: output/latest.zip
        continue-on-error: true

      - name: Clone plugin hosting repo
        run: git clone https://github.com/${{ github.repository_owner }}/MyDalamudPlugins.git
        env:
          GIT_TERMINAL_PROMPT: 0

      - name: Copy zip to plugins folder
        run: |
          Copy-Item output/latest.zip -Destination MyDalamudPlugins/plugins/${{ env.PLUGIN_NAME }}/latest.zip -Force
          Copy-Item output/${{ env.PLUGIN_NAME }}.json -Destination MyDalamudPlugins/plugins/${{ env.PLUGIN_NAME }}/${{ env.PLUGIN_NAME }}.json -Force

      - name: Update repo.json with version and timestamp
        shell: pwsh
        run: |
          $pluginJsonPath = "${{ env.PLUGIN_NAME }}/bin/Release/${{ env.PLUGIN_NAME }}.json"
          $pluginJson = Get-Content $pluginJsonPath | ConvertFrom-Json
          $repoJsonPath = "MyDalamudPlugins/repo.json"
          $repoJsonRaw = Get-Content $repoJsonPath -Raw
          $repoJson = $repoJsonRaw | ConvertFrom-Json
          
          if ($repoJson -isnot [System.Collections.IList]) {
            $repoJson = @($repoJson)
          }
          
          foreach ($plugin in $repoJson) {
            if ($plugin.InternalName -eq $pluginJson.InternalName) {
              $plugin.DalamudApiLevel = $pluginJson.DalamudApiLevel
              $plugin.AssemblyVersion = $pluginJson.AssemblyVersion
              $plugin.LastUpdated = [int][double]::Parse((Get-Date -UFormat %s))
            }
          }
          
          $repoJson | ConvertTo-Json -Depth 100 | Set-Content $repoJsonPath

      - name: Commit and push to MyDalamudPlugins
        run: |
          cd MyDalamudPlugins
          git config user.name "github-actions"
          git config user.email "github-actions@github.com"
          git add .
          git commit -m "Update ${{ env.PLUGIN_NAME }} to ${{ github.event.release.tag_name }}"
          git push https://x-access-token:${{ secrets.MYDALAMUDPLUGINS_TOKEN }}@github.com/${{ github.repository_owner }}/MyDalamudPlugins.git HEAD:main
