name: Publish JetBrains Plugin

on:
  workflow_call:
    inputs:
      ref:
        description: "Git ref to checkout (tag or branch)"
        type: string
        required: false
        default: ""
    secrets:
      JETBRAINS_CERTIFICATE_CHAIN:
        description: "JetBrains plugin signing certificate chain"
        required: true
      JETBRAINS_PRIVATE_KEY:
        description: "JetBrains plugin signing private key"
        required: true
      JETBRAINS_PRIVATE_KEY_PASSWORD:
        description: "JetBrains plugin signing private key password"
        required: true
      JETBRAINS_PUBLISH_TOKEN:
        description: "JetBrains Marketplace publish token"
        required: true
  workflow_dispatch:

concurrency:
  group: jetbrains-publish
  cancel-in-progress: false

permissions:
  contents: write

jobs:
  publish:
    name: Publish to JetBrains Marketplace
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ inputs.ref || github.ref }}

      - name: Free disk space
        run: |
          sudo rm -rf /usr/share/dotnet
          sudo rm -rf /usr/local/lib/android
          sudo rm -rf /opt/ghc
          sudo rm -rf /opt/hostedtoolcache/CodeQL
          sudo docker image prune --all --force
          df -h

      - name: Setup Java
        uses: actions/setup-java@v4
        with:
          distribution: "temurin"
          java-version: "17"

      - name: Setup Gradle
        uses: gradle/actions/setup-gradle@v3

      - name: Build Plugin
        working-directory: jetbrains-plugin
        run: ./gradlew buildPlugin

      - name: Verify Plugin
        working-directory: jetbrains-plugin
        run: ./gradlew verifyPlugin

      - name: Sign Plugin
        working-directory: jetbrains-plugin
        env:
          CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
          PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
          PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
        run: ./gradlew signPlugin

      - name: Publish to JetBrains Marketplace
        working-directory: jetbrains-plugin
        env:
          PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
        run: ./gradlew publishPlugin
