name: Snapshot backup
env:
  BACKUP_BUCKET: "gs://example-prod-backups"
  FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
on:
  schedule:
    # At some schedule when your app is least active
    - cron: "0 3 * * *"

jobs:
  backup-firestore:
    runs-on: ubuntu-latest
    steps:
      - name: Setup gcloud environment
        uses: GoogleCloudPlatform/github-actions@0.1.2
        with:
          project_id: example-prod
          service_account_key: ${{ secrets.GCLOUD_AUTH_KEY_PROD }}

      - name: Select project
        run: gcloud config set project example-prod

      - name: Remove previous nightly backup
        run: gsutil rm -rf ${{ env.BACKUP_BUCKET }}/firestore/snapshot

      - name: Export Firestore to Cloud Storage bucket
        run: gcloud firestore export ${{ env.BACKUP_BUCKET }}/firestore/snapshot --async

  backup-rtdb:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Setup gcloud environment
        uses: GoogleCloudPlatform/github-actions@0.1.2
        with:
          project_id: example-prod
          service_account_key: ${{ secrets.GCLOUD_AUTH_KEY_PROD }}

      - name: Select project
        run: gcloud config set project example-prod

      - name: Select Firebase project
        uses: w9jds/firebase-action@v1.3.0
        with:
          args: use production

      - name: Download RTDB data
        uses: w9jds/firebase-action@v1.3.0
        with:
          args: database:get --output snapshot.json /

      - name: Remove previous nightly backup
        run: gsutil rm -f ${{ env.BACKUP_BUCKET }}/rtdb/snapshot.json

      - name: Upload to Cloud Storage Bucket
        run: gsutil cp snapshot.json ${{ env.BACKUP_BUCKET }}/rtdb