name: Vercel Production Deployments
on:
  push:
    branches:
      - main
      - next
  pull_request:
    branches:
      - main
      - next

env:
  VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
  VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
  VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
  GITHUB_TOKEN: ${{ secrets.ACTIONS_PAT_GITHUB }}
  BRANCH: ${{ github.ref_name }}

jobs:
  deploy_book:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout the Repository
        uses: actions/checkout@v3
      - name: Decide Deployment Environment
        id: deployment_environment
        run: |
          if [[ ${{ env.BRANCH }} == "main" ]]; then
            echo "PROJECT_ENVIRONMENT=production" >> $GITHUB_ENV
          else
            echo echo "PROJECT_ENVIRONMENT=preview" >> $GITHUB_ENV
          fi
      - name: Setup NodeJS
        uses: actions/setup-node@v3
        with:
          node-version: '18'
      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 8
          run_install: false
      - name: Get pnpm store directory
        shell: bash
        run: |
          echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
      - uses: actions/cache@v3
        name: Setup pnpm cache
        with:
          path: ${{ env.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-
      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@master
        id: rust-toolchain
        with:
          toolchain: stable
      - name: Cache dependencies
        uses: Swatinem/rust-cache@6fd3edff6979b79f87531400ad694fb7f2c84b1f # v2.2.1
      - name: Install cross
        uses: taiki-e/install-action@v2
        with:
          tool: cargo-binstall
      - name: Install dependencies
        run: cargo binstall mdbook mdbook-plantuml mdbook-inline-highlighting
      - name: Install dependencies
        run: pnpm install -g vercel@latest
      - name: Populate Preview Variables
        run: vercel pull --yes --environment=${{env.PROJECT_ENVIRONMENT}} --token=${{ env.VERCEL_TOKEN }}
      - name: Build the Book
        run: mdbook build guide
      - name: Build for Vercel deployment
        run: vercel build --cwd guide/book -y -d
      - name: Deploy to Vercel -- Preview
        if: env.PROJECT_ENVIRONMENT == 'preview'
        run: vercel deploy --cwd guide/book --prebuilt --token=${{ env.VERCEL_TOKEN }}
      - name: Deploy to Vercel -- Production
        if: env.PROJECT_ENVIRONMENT == 'production'
        run: vercel deploy --cwd guide/book --prod --prebuilt --token=${{ env.VERCEL_TOKEN }}
