# Tauri v2 Windows 自动构建 + 签名 + 阿里云 OSS 发布
# 完整部署教程与踩坑指南见 docs/tauri-cicd-guide.md
name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: windows-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v4
        with:
          version: 9

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'pnpm'

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Rust cache
        uses: swatinem/rust-cache@v2
        with:
          workspaces: './src-tauri -> target'

      - run: pnpm install --frozen-lockfile

      # 诊断：确认签名密钥已注入
      - name: Verify signing key
        shell: pwsh
        env:
          TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
        run: |
          if ([string]::IsNullOrEmpty($env:TAURI_SIGNING_PRIVATE_KEY)) {
            Write-Error "TAURI_SIGNING_PRIVATE_KEY is EMPTY - update bundles will not be generated!"
            exit 1
          }
          $lines = $env:TAURI_SIGNING_PRIVATE_KEY.Split("`n").Count
          Write-Host "TAURI_SIGNING_PRIVATE_KEY is set ($lines lines)"

      # 先创建 GitHub Release（解决 tauri-action 权限问题）
      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.ref_name }}
          name: 炼境 ${{ github.ref_name }}
          body: |
            ## 更新内容
            请查看提交记录了解详情。
          draft: false
          prerelease: false

      # 构建 Tauri 应用，tauri-action 发现已有 Release 后只上传文件
      - name: Build & Release
        uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
          TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
        with:
          tagName: ${{ github.ref_name }}
          releaseName: 炼境 ${{ github.ref_name }}
          releaseBody: |
            ## 更新内容
            请查看提交记录了解详情。
          releaseDraft: false
          prerelease: false
          args: --verbose

      # 上传到阿里云 OSS + 生成 latest.json
      - name: Upload to OSS & generate latest.json
        shell: pwsh
        env:
          OSS_KEY_ID: ${{ secrets.OSS_KEY_ID }}
          OSS_KEY_SECRET: ${{ secrets.OSS_KEY_SECRET }}
          OSS_BUCKET: ${{ secrets.OSS_BUCKET }}
          OSS_ENDPOINT: ${{ secrets.OSS_ENDPOINT }}
        run: |
          # 下载 ossutil
          $oss = "$env:GITHUB_WORKSPACE\ossutil64.exe"
          Invoke-WebRequest -Uri "https://gosspublic.alicdn.com/ossutil/1.7.17/ossutil-v1.7.17-windows-amd64.zip" -OutFile oss.zip
          Expand-Archive oss.zip -DestinationPath oss_tmp
          $exeFound = Get-ChildItem oss_tmp -Filter "ossutil*.exe" -Recurse | Select-Object -First 1
          Copy-Item $exeFound.FullName $oss

          # 直接在本步骤找文件，不依赖 step outputs
          $tag     = "${{ github.ref_name }}"
          $version = $tag.TrimStart('v')
          $nsisDir = "$env:GITHUB_WORKSPACE\src-tauri\target\release\bundle\nsis"

          Write-Host "=== bundle dir (all) ==="
          Get-ChildItem "$env:GITHUB_WORKSPACE\src-tauri\target\release\bundle" -Recurse | ForEach-Object { Write-Host $_.FullName }

          $all       = Get-ChildItem $nsisDir
          # Tauri v2: 更新包是 .exe + .exe.sig（不再是 .nsis.zip）
          $installer = $all | Where-Object { $_.Name.EndsWith('-setup.exe') } | Select-Object -First 1
          $sigFile   = $all | Where-Object { $_.Name.EndsWith('-setup.exe.sig') } | Select-Object -First 1

          Write-Host "installer : $($installer?.FullName)"
          Write-Host "sigFile   : $($sigFile?.FullName)"

          if (-not $installer) { Write-Error "installer not found!"; exit 1 }

          $bucket   = "oss://$env:OSS_BUCKET"
          $endpoint = "https://$env:OSS_ENDPOINT"

          & $oss config -e $endpoint -i $env:OSS_KEY_ID -k $env:OSS_KEY_SECRET -L CH

          & $oss cp $installer.FullName "$bucket/releases/$tag/$($installer.Name)" -f

          if ($sigFile) {
            & $oss cp $sigFile.FullName "$bucket/releases/$tag/$($sigFile.Name)" -f

            # 生成 latest.json（Tauri v2 格式：url 指向 .exe，signature 来自 .exe.sig）
            $date    = (Get-Date -Format 'yyyy-MM-ddTHH:mm:ssZ')
            $baseUrl = "https://$env:OSS_BUCKET.$env:OSS_ENDPOINT/releases/$tag"
            $sig     = (Get-Content $sigFile.FullName -Raw).Trim()

            $json = [ordered]@{
              version  = $version
              pub_date = $date
              notes    = "版本 $tag 已发布"
              platforms = [ordered]@{
                'windows-x86_64' = [ordered]@{
                  signature = $sig
                  url       = "$baseUrl/$($installer.Name)"
                }
              }
            } | ConvertTo-Json -Depth 5

            $json | Out-File -FilePath latest.json -Encoding utf8NoBOM
            Write-Host "=== latest.json ==="
            Get-Content latest.json

            & $oss cp latest.json "$bucket/latest.json" -f
            Write-Host "latest.json uploaded"
          } else {
            Write-Warning "sigFile (.exe.sig) not found — skipping updater upload"
          }
