name: Publish to CWS + EWS on Chromium version bump

on:
  push:
    branches: [main]
    paths: [chromium/extension/manifest.json]

jobs:
  check-version-to-publish:
    runs-on: ubuntu-latest
    steps:

      - name: Checkout adamlui/chatgpt-auto-continue
        uses: actions/checkout@v4
        with:
          sparse-checkout: chromium
          fetch-depth: 2

      - name: Check Chromium manifest for version bump
        run: |
          current_ver=$(cat chromium/extension/manifest.json | grep '"version"' | sed -E 's/.*"version": "(.*)".*/\1/')
          prev_ver=$(git show HEAD^:chromium/extension/manifest.json | grep '"version"' | sed -E 's/.*"version": "(.*)".*/\1/')
          if [ "$current_ver" != "$prev_ver" ] ; then
               echo "Extension updated from $prev_ver to $current_ver"
               echo "VERSION_CHANGED=true" >> $GITHUB_ENV
          else echo "VERSION_CHANGED=false" >> $GITHUB_ENV ; fi

      - name: Create zipball
        if: env.VERSION_CHANGED == 'true'
        run: |
          cd chromium/extension
          zip -r ../../extension.zip .

      - name: Publish to CWS
        if: env.VERSION_CHANGED == 'true'
        uses: mobilefirstllc/cws-publish@latest
        with:
          action: publish
          extension_id: lbojnhaafilddefkdgmbplkafnckaoga
          client_id: ${{ secrets.CWS_CLIENT_ID }}
          client_secret: ${{ secrets.CWS_CLIENT_SECRET }}
          refresh_token: ${{ secrets.CWS_REFRESH_TOKEN }}
          zip_file: extension.zip
        continue-on-error: true

      - name: Publish to EWS
        if: env.VERSION_CHANGED == 'true'
        uses: wdzeng/edge-addon@v2
        with:
          product-id: ${{ secrets.EWS_PRODUCT_ID }}
          client-id: ${{ secrets.EWS_CLIENT_ID }}
          api-key: ${{ secrets.EWS_CLIENT_SECRET }}
          zip-path: extension.zip
        continue-on-error: true
