name: update swagger files

on:
  schedule:
    - cron:  '0 */12 * * *' # every 12 hours on the hour
  workflow_dispatch:

jobs:
  update-swagger:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - run: |
          wget https://raw.githubusercontent.com/go-gitea/gitea/refs/heads/main/templates/swagger/v1_json.tmpl
          sed -i "$@" 's\"version": "{{AppVer | JSEscape}}"\"version": "dev"\' v1_json.tmpl
          sed -i "$@" 's\"basePath": "{{AppSubUrl | JSEscape}}/api/v1"\"basePath": "https://gitea.com/api/v1"\' v1_json.tmpl
          mv v1_json.tmpl static/swagger-latest.json

          for ver in '1.24.7' '1.23.8' '1.22.6' '1.21.11' '1.20.6' '1.19.4'; do
            wget https://raw.githubusercontent.com/go-gitea/gitea/refs/tags/v${ver}/templates/swagger/v1_json.tmpl
            sed -i "$@" "s|\"version\": \"{{AppVer \| JSEscape}}\"|\"version\": \"${ver}\"|" v1_json.tmpl
            sed -i "$@" 's\"basePath": "{{AppSubUrl | JSEscape}}/api/v1"\"basePath": "https://gitea.com/api/v1"\' v1_json.tmpl
            # for version < 1.21.11
            sed -i "$@" "s|\"version\": \"{{AppVer \| JSEscape \| Safe}}\"|\"version\": \"${ver}\"|" v1_json.tmpl
            sed -i "$@" 's\"basePath": "{{AppSubUrl | JSEscape | Safe}}/api/v1"\"basePath": "https://gitea.com/api/v1"\' v1_json.tmpl
            minor=$(echo "$ver" | cut -d '.' -f 2)
            mv v1_json.tmpl static/swagger-$minor.json
          done

          if ! [[ $(git diff --shortstat) ]]; then exit 0; fi
          git config --global user.name "Gitea Bot"
          git config --global user.email "teabot@gitea.io"
          git remote set-url origin https://x-access-token:${{ secrets.DEPLOY_TOKEN }}@gitea.com/gitea/docs.git
          git add --all
          git commit -m "[skip ci] Updated swagger files"
          git push
