name: Deploy function updates ( main )

on:
  # Trigger: on new tag push
  push:
    branches:
      - main
    paths:
      - '.github/workflows/deploy-minter.yml'
      - 'functions/**'

jobs:
  build:
    name: Publish changes

    runs-on: ubuntu-latest

    steps:
      # Get the repo files from current commit
      - name: Cloning repository
        uses: actions/checkout@v1

      # Install frontend dependencies based on nvmrc
      - name: Read .nvmrc
        run: echo "##[set-output name=NVMRC;]$(cat .nvmrc)"
        id: nvmfunctions
        working-directory: functions

      - name: Set Node.js (.nvmrc)
        uses: actions/setup-node@v1
        with:
          node-version: "${{ steps.nvmfunctions.outputs.NVMRC }}"

      - name: Install functions dependencies
        run: npm i
        working-directory: functions

      # Backup firestore before deploying to database
      - name: 'Set up gcloud cli'
        uses: google-github-actions/setup-gcloud@master
        with:
          service_account_key: "${{ secrets.GCP_SERVICE_ACCOUT_JSON_PRODUCTION }}"
          export_default_credentials: true

      # Note to self: needs IAM permissions
      # see https://firebase.google.com/docs/firestore/manage-data/export-import
      - name: Backup firestore
        run: |
          gcloud config set project ${{ secrets.FIREBASE_PROJECT_ID_PRODUCTION }}
          echo "Project is now set to ${{ secrets.FIREBASE_PROJECT_ID_PRODUCTION }}"
          gcloud firestore export ${{ secrets.GCP_BUCKET_LINK_PRODUCTION }}/firestore-backups/$(date +'%Y-%m-%d-%s')/

          
      - name: Deploy to Firebase
        uses: w9jds/firebase-action@master
        with:
          args: deploy --only=functions
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
