name: Deploy backend to beta VPS

# On a push to `main` that touches backend/**, SSH to beta and roll ONLY the
# backend service onto the image backend-build-push.yml just published for
# this commit. Frontend is deployed independently by frontend-deploy.yml --
# the FE/BE CI-CD split survives reunification intact: a backend change ships
# without touching frontend and vice versa. infra/deploy/deploy.sh persists
# each service's live tag host-side, so a single-service roll never disturbs
# the other. An infra-only push rolls nothing (infra-sync.yml syncs the
# host checkouts instead); a mixed backend+frontend push fires both deploy
# workflows, serialized host-side by deploy.sh's flock.
#
# The SSH_HOST/USER/KEY/PORT secrets point at beta. appleboy/ssh-action is
# referenced by full GitHub URL because it isn't mirrored in Forgejo's default
# action registry.
#
# The tag MUST match backend-build-push.yml's `sha-${GITHUB_SHA:0:12}` (12
# hex), not the full 40-char ${{ github.sha }} -- default Actions expressions
# have no substring function, so the compute step below truncates it.
# deploy.sh also retries the pull for ~5 min because Forgejo `needs:` can't
# gate across the separate build-push workflow, so this push's build may still
# be in flight.

on:
  push:
    branches: [main]
    paths: ['backend/**']
  workflow_dispatch: {}

concurrency:
  group: beta-deploy-backend
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: docker
    steps:
      - uses: actions/checkout@v4
        # fetch-depth 0: the tag is keyed to the LAST COMMIT THAT TOUCHED THIS
        # DOMAIN, not the branch tip -- in a path-filtered monorepo the tip is
        # often an unrelated domain's commit, and a depth-1 clone can't see
        # past it to find the real key.
        with:
          fetch-depth: 0

      - name: Compute image tag (last backend-touching commit)
        id: tag
        run: |
          domain_sha="$(git log -1 --format=%H -- backend/)"
          echo "tag=sha-${domain_sha:0:12}" >> "$GITHUB_OUTPUT"

      - name: Deploy backend over SSH
        uses: https://github.com/appleboy/ssh-action@v1.2.0
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ secrets.SSH_PORT }}
          # Forward the target service + the image tag to run. deploy.sh reads
          # BACKEND_IMAGE_TAG and rolls just `backend`.
          envs: SERVICE,BACKEND_IMAGE_TAG
          script: /opt/thermograph/infra/deploy/deploy.sh
        env:
          SERVICE: backend
          BACKEND_IMAGE_TAG: ${{ steps.tag.outputs.tag }}
