name: Build & Deploy
on:
  push:
    branches:
      - main
      - release

jobs:
  build:
    runs-on: [ ubuntu-22.04 ]
    steps:
      - uses: actions/checkout@v4

      - name: Build Docker image
        run: docker build -t barotrauma-server:${{ github.sha }} .

      - name: Tag and push to local registry
        if: github.ref_name == 'release'
        run: |
          docker tag barotrauma-server:${{ github.sha }} \
            ${{ secrets.REGISTRY_ADDR }}/barotrauma-server:latest
          docker push ${{ secrets.REGISTRY_ADDR }}/barotrauma-server:latest

      - name: Deploy via SSH
        if: github.ref_name == 'release'
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SSH_KEY }}
          script: |
            docker pull ${{ secrets.REGISTRY_ADDR }}/barotrauma-server:latest
            docker stop barotrauma 2>/dev/null || true
            docker rm barotrauma 2>/dev/null || true
            docker run -d --name barotrauma \
              --restart unless-stopped \
              -p 27015:27015/udp \
              -p 27015:27015/tcp \
              ${{ secrets.REGISTRY_ADDR }}/barotrauma-server:latest
            docker system prune -f
