# .github/workflows/deploy.yml
#
# Builds the Docker image, pushes it to a private DigitalOcean Container
# Registry, then SSHes into the droplet to pull + restart the container.
#
# Required repo secrets (Settings → Secrets and variables → Actions):
#   DO_REGISTRY_TOKEN  — DO API token with registry read+write (CI push)
#   DROPLET_HOST       — droplet public IPv4
#   DROPLET_USER       — deploy user on the droplet (e.g. "deploy")
#   DROPLET_SSH_KEY    — private SSH key (full contents, incl. BEGIN/END lines)
#
# Replace <registry-name> and <app-name> below.

name: Build and Deploy

on:
  push:
    branches: [main]

env:
  REGISTRY: registry.digitalocean.com
  REGISTRY_NAME: <registry-name>
  IMAGE_NAME: <app-name>

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      # Installs doctl and authenticates it with your read+write token
      - name: Install doctl
        uses: digitalocean/action-doctl@v2
        with:
          token: ${{ secrets.DO_REGISTRY_TOKEN }}

      # Short-lived (20 min) Docker credentials so the push steps can authenticate
      - name: Log in to DO Container Registry
        run: doctl registry login --expiry-seconds 1200

      - name: Build image
        run: |
          docker build \
            -t $REGISTRY/$REGISTRY_NAME/$IMAGE_NAME:latest \
            -t $REGISTRY/$REGISTRY_NAME/$IMAGE_NAME:${{ github.sha }} \
            .

      - name: Push image
        run: |
          docker push $REGISTRY/$REGISTRY_NAME/$IMAGE_NAME:latest
          docker push $REGISTRY/$REGISTRY_NAME/$IMAGE_NAME:${{ github.sha }}

      # SSH in and roll the container to the freshly-pushed image
      - name: Deploy to droplet
        uses: appleboy/ssh-action@v1.2.0
        with:
          host: ${{ secrets.DROPLET_HOST }}
          username: ${{ secrets.DROPLET_USER }}
          key: ${{ secrets.DROPLET_SSH_KEY }}
          script: |
            cd /opt/app
            docker compose pull
            docker compose up -d
            docker image prune -f
