name: Deploy GitHub Pages

on:
  push:
    branches: [ <%=yamlDefaultBranch%> ]
  workflow_dispatch: {}

jobs:
  build-and-deploy:

    runs-on: ubuntu-latest

    permissions:
      pages: write
      id-token: write
      actions: read

    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}

    strategy:
      matrix:
        node-version: [22.x]

    steps:
    - uses: actions/checkout@v3
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
        # cache: 'npm' # enable after committing lock file from first install
    - run: npm i # replace with 'npm ci' after committing lock file from first install
    - name: Set project name
      run: echo "PROJECT_NAME=$(jq -r '.name' package.json)" >> $GITHUB_ENV
    - name: Build project with dynamic base-href
      run: npm run build -- --base-href "/${{ github.event.repository.name }}/"
    - name: Update Resource Paths
      run: find ./dist/${{ env.PROJECT_NAME }}/browser -type f -name '*.js' -exec sed -i -e "s|/assets|/${{ github.event.repository.name }}/assets|g" -e "s|url('/assets|url('/${{ github.event.repository.name }}/assets|g" {} +
    - name: SPA routing handling
      run: cp ./dist/${{ env.PROJECT_NAME }}/browser/index.html ./dist/${{ env.PROJECT_NAME }}/browser/404.html
    - name: Upload build artifact to GitHub Pages
      uses: actions/upload-pages-artifact@v3
      with:
        path: ./dist/${{ env.PROJECT_NAME }}/browser
    - name: Deploy to GitHub Pages
      uses: actions/deploy-pages@v4
