name: Publish website

on:
  workflow_dispatch:
  pull_request:
    paths:
      - docs/**
      - .github/workflows/update-website.yml
  push:
    branches:
      - main
    paths:
      - docs/**
      - .github/workflows/update-website.yml

jobs:
  build_and_deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    container: asterinas/asterinas:0.10.1
    steps:
      - uses: actions/checkout@v2
        with:
          repository: 'asterinas/asterinas'
          path: 'asterinas'
      
      - name: Build the website
        run: |
          cd asterinas/docs
          mdbook build

      - name: Deploy website
        if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
        env:
          BOOK_PUBLISH_KEY: ${{ secrets.BOOK_PUBLISH_KEY }}
        run: |
          echo "$BOOK_PUBLISH_KEY\n" > ./book_publish_key
          chmod 600 ./book_publish_key
          ssh-keygen -y -f ./book_publish_key > /dev/null
          ssh-keyscan -t rsa github.com >> ./known_hosts
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git config --global user.name "github-actions[bot]"
          GIT_SSH_COMMAND="ssh -i ./book_publish_key -o UserKnownHostsFile=./known_hosts" \
            git clone git@github.com:asterinas/book.git temp_book
          cd temp_book
          git checkout --orphan newBranch
          git rm -rf *
          cp -r ../asterinas/docs/book/* ./
          git add -A
          git commit -am "Update website"
          git branch -D main
          git branch -m main
          GIT_SSH_COMMAND="ssh -i ../book_publish_key -o UserKnownHostsFile=../known_hosts" \
            git push -f origin main
