name: Deploy Docs

on:
  push:
    paths:
      - "vitepress-docs/**"
    tags:
      - "*"
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - uses: pnpm/action-setup@v3
        name: Install pnpm
        id: pnpm-install
        with:
          version: 8
          run_install: false

      - name: check github release done
        run: |
          for ((attempt=1; attempt<=10; attempt++)); do
              if wget -q --spider "https://github.com/dreamhunter2333/cloudflare_temp_email/releases/latest/download/frontend.zip"; then
                  echo "frontend.zip found."
                  break
              else
                  if [ $attempt -eq 10 ]; then
                      echo "Exceeded maximum retries. frontend.zip not found."
                  else
                      echo "frontend.zip not found. Retrying in 30 seconds..."
                      sleep 30
                  fi
              fi
          done

      - name: Deploy Docs for ${{github.ref_name}}
        run: |
          cd vitepress-docs/
          wget https://github.com/dreamhunter2333/cloudflare_temp_email/releases/latest/download/frontend.zip  -O docs/public/ui_install/frontend.zip
          pnpm install --no-frozen-lockfile
          if [[ ${{github.ref}} == refs/tags/* ]]; then
            export TAG_NAME=${{github.ref_name}}
          else
            export TAG_NAME=$(git describe --tags --abbrev=0)
          fi
          echo "Deploying docs for tag $TAG_NAME"
          pnpm run deploy
        env:
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
