name: "Deploy to Staging"

on:
  pull_request_target:
    types: [labeled]
  workflow_dispatch:
    inputs:
      server:
        description: "Staging Server"
        type: choice
        required: true
        options:
          - staging.openfoodnetwork.org.uk
          - staging.openfoodnetwork.org.au
          - staging.coopcircuits.fr
      commit_ref:
        description: "Commit Reference"
        type: string
        required: false

jobs:
  deploy_pr:
    if: contains(fromJSON('["pr-staged-uk", "pr-staged-au", "pr-staged-fr"]'), github.event.label.name)
    runs-on: ubuntu-latest
    steps:
      - name: "Check user has write access"
        uses: "lannonbr/repo-permission-check-action@2.0.2"
        with:
          permission: "write"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Configure deployment key
        if: success()
        run: |
          install -m 600 -D /dev/null ~/.ssh/id_rsa
          echo "${{ secrets.DEPLOYMENT_KEY }}" > ~/.ssh/id_rsa
          echo "${{ secrets.DEPLOYMENT_HOSTS }}" > ~/.ssh/known_hosts

      - name: Deploy to Staging
        if: success()
        run: |
          ssh ofn-deploy@${{ github.event.label.description }} -o LogLevel=ERROR "pull-request-${{ github.event.pull_request.number }} ."

  deploy_branch:
    if: ${{ inputs.server }}
    runs-on: ubuntu-latest
    steps:
      - name: "Check user has write access"
        uses: "lannonbr/repo-permission-check-action@2.0.2"
        with:
          permission: "write"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          
      - name: Configure deployment key
        if: success()
        run: |
          install -m 600 -D /dev/null ~/.ssh/id_rsa
          echo "${{ secrets.DEPLOYMENT_KEY }}" > ~/.ssh/id_rsa
          echo "${{ secrets.DEPLOYMENT_HOSTS }}" > ~/.ssh/known_hosts

      - name: Deploy to Staging
        if: success()
        run: |
          ssh ofn-deploy@${{ inputs.server }} -o LogLevel=ERROR "$GITHUB_REF_NAME ${{ inputs.commit_ref || github.sha }}"
