name: MDBOOK

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
  cancel-in-progress: true

on:
  workflow_dispatch:
    inputs:
      logLevel:
        description: 'Log level'
        required: true
        default: 'info'
  push:
    branches: [ master ]
    paths:
      - 'docs/**'
  pull_request:
    branches: [ master ]
    paths:
      - 'docs/**'

jobs:
  lint-markdown:
    if: ${{ github.event_name != 'push' }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Ensure git safe directory
        run: |
          git config --global --add safe.directory $(pwd)

      - name: Lint markdown format
        uses: github/super-linter/slim@v5
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          DEFAULT_BRANCH: master
          FILTER_REGEX_INCLUDE: .*docs/.*md$
          VALIDATE_ALL_CODEBASE: false
          VALIDATE_MARKDOWN: true

  build-mdbook:
    needs: lint-markdown
    if: |
      always()
      && (needs.lint-markdown.result == 'success' || needs.lint-markdown.result == 'skipped')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Ensure git safe directory
        run: |
          git config --global --add safe.directory $(pwd)

      - name: Setup mdBook
        uses: peaceiris/actions-mdbook@v1
        with:
          mdbook-version: 'latest'

      - name: Install mdBook preprocessors
        run: |
          cargo install mdbook-variables --locked

      - name: Create work dir
        run: |
          cd docs/book/
          mkdir target

      - name: Build English version
        run: |
          cd docs/book/en
          mdbook build
          cp -r book ../target/en

      - name: Publish EN version
        if: ${{ github.event_name == 'push' }}
        uses: cpina/github-action-push-to-another-repository@main
        env:
          API_TOKEN_GITHUB: ${{ secrets.API_TOKEN_GITHUB_WWW }}
        with:
          source-directory: 'docs/book/target'
          destination-github-username: 'WasmEdge'
          destination-repository-name: 'www'
          target-directory: 'book'
          user-email: michael@secondstate.io
          target-branch: main
