name: Deploy Website
on:
  push:
    branches:
      - main
    paths-ignore:
      - 'worker/*'
      - '.devcontainer/*'
  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
concurrency:
  group: "website_deploy"
  cancel-in-progress: true

jobs:
  deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - name: Checkout repo
        uses: actions/checkout@v4
      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v3
        with:
          hugo-version: '0.147.7'
          extended: true
      - name: Build website
        run: hugo --minify --baseURL "https://www.dataforcanada.org/"
      - name: Install rclone
        run: curl https://rclone.org/install.sh | sudo bash
      - name: Configure rclone for Cloudflare R2
        run: |
          mkdir -p ~/.config/rclone
          echo "[cloudflare]" > ~/.config/rclone/rclone.conf
          echo "type = s3" >> ~/.config/rclone/rclone.conf
          echo "provider = Cloudflare" >> ~/.config/rclone/rclone.conf
          echo "access_key_id = ${{ secrets.R2_ACCESS_KEY_ID }}" >> ~/.config/rclone/rclone.conf
          echo "secret_access_key = ${{ secrets.R2_SECRET_ACCESS_KEY }}" >> ~/.config/rclone/rclone.conf
          echo "endpoint = ${{ secrets.R2_ENDPOINT }}" >> ~/.config/rclone/rclone.conf
      - name: Upload to Cloudflare R2
        run: |
          rclone sync --progress public/ cloudflare:/${{ secrets.R2_BUCKET }}
      - name: Purge Cloudflare cache
        run: |
          curl --location 'https://api.cloudflare.com/client/v4/zones/${{ secrets.CLOUDFLARE_ZONE_ID }}/purge_cache' \
            --header 'Content-Type: application/json' \
            --header 'Authorization: Bearer ${{ secrets.CLOUDFLARE_API_TOKEN_PURGE_CACHE }}' \
            --data '{"hosts": ["www.dataforcanada.org"]}'
