name: Deploy Main

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  deploy:
    if: github.repository == 'pagefaultgames/pokerogue'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: 'recursive'
      - uses: actions/setup-node@v4
        with:
          node-version: "20"
      - name: Install dependencies
        run: npm ci
      - name: Build
        run: npm run build
        env:
          NODE_ENV: production
      - name: Set up SSH
        if: github.event_name == 'push' && github.ref_name == 'main'
        run: |
          mkdir ~/.ssh
          echo "${{ secrets.SSH_PUBLIC_KEY }}" > ~/.ssh/id_ed25519.pub
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/*
          ssh-keyscan -H ${{ secrets.SSH_HOST }} >> ~/.ssh/known_hosts
      - name: Deploy build on server
        if: github.event_name == 'push' && github.ref_name == 'main'
        run: | 
          rsync --del --no-times --checksum -vrm dist/* ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}:${{ secrets.DESTINATION_DIR }}
          ssh -t ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }} "~/prmanifest --inpath ${{ secrets.DESTINATION_DIR }} --outpath ${{ secrets.DESTINATION_DIR }}/manifest.json"
      - name: Purge Cloudflare Cache
        if: github.event_name == 'push' && github.ref_name == 'main'
        id: purge-cache
        uses: NathanVaughn/actions-cloudflare-purge@v3.1.0
        with:
          cf_auth: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          cf_zone: ${{ secrets.CLOUDFLARE_ZONE_ID }}
          files: |
            https://pokerogue.net/
            https://pokerogue.net/index.html
            https://pokerogue.net/manifest.json
            https://pokerogue.net/manifest.webmanifest
            https://pokerogue.net/service-worker.js