name: generate api pages
on:
  workflow_dispatch:
    inputs:
      tag:
        description: 'Netbird release tag version'
        required: true
        default: "refs/tags/vX.Y.Z"
        type: string

jobs:
  generate_api_pages:
    runs-on: macos-latest
    steps:
      - name: Parse tag input
        id: semver_parser
        uses: booxmedialtd/ws-action-parse-semver@v1
        with:
          input_string: ${{ github.event.inputs.tag }}
          version_extractor_regex: '\/v(.*)$'

      - uses: actions/checkout@v2
        with:
          token: ${{ secrets.DEV_GITHUB_TOKEN }}

      - name: Create directory
        run: mkdir -p generator/openapi

      - name: Download openapi.yml
        run: curl -L -o generator/openapi/openapi.yml "https://raw.githubusercontent.com/netbirdio/netbird/v${{ steps.semver_parser.outputs.fullversion }}/management/server/http/api/openapi.yml"

      - name: Install Go
        uses: actions/setup-go@v3
        with:
          go-version: '1.21.1'

      - name: Build Go project
        run: (cd ./generator && go build -o expandOpenAPIRef)

      - name: Expand openapi.yml
        run: (cd ./generator && ./expandOpenAPIRef)

      - name: Remove old generated files
        run: rm -rf src/pages/ipa/resources/*

      - name: Npm install
        run: npm install

      - name: Generate api pages for netbird main openapi definition
        run: npx ts-node generator/index.ts gen --input generator/openapi/expanded.yml --output src/pages/ipa/resources

      - name: Check git diff and send to output
        id: git_diff
        run: |
          if git --no-pager diff --exit-code; then
            echo "changed=false" >> "$GITHUB_OUTPUT"
          else
            echo "changed=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Commit and push changes
        if: steps.git_diff.outputs.changed == 'true'
        run: |
          git config --global user.email "dev@netbird.io"
          git config --global user.name "netbirddev"

          git add -A
          git commit -m "Update API pages with v${{ steps.semver_parser.outputs.fullversion }}"
          git push
