name: Deploy Utopia Dev

on:
  push:
    branches:
      - dev

concurrency:
  group: ${{ gitea.workflow }}-${{ gitea.ref }}
  cancel-in-progress: true

jobs:
  deploy:
    runs-on: ubuntu-24.04

    steps:
      - name: Deploy to server via SSH
        uses: appleboy/ssh-action@v1.2.5
        with:
          host: ${{ secrets.SSH_HOST_DEV }}
          username: ${{ secrets.SSH_USER_DEV }}
          password: ${{ secrets.SSH_PASSWORD_DEV }}
          port: ${{ secrets.SSH_PORT_DEV }}
          script: |
            cd ~/deploy/utopiadev
            echo "Pulling latest code..."
            git pull
            echo "Starting deployment..."
            sh start.sh
            echo "Deploy done"

  cleanup:
    runs-on: ubuntu-24.04
    needs: deploy
    if: always()
    steps:
      - name: Cleanup Docker on server
        uses: appleboy/ssh-action@v1.2.5
        with:
          host: ${{ secrets.SSH_HOST_DEV }}
          username: ${{ secrets.SSH_USER_DEV }}
          password: ${{ secrets.SSH_PASSWORD_DEV }}
          port: ${{ secrets.SSH_PORT_DEV }}
          script: |
            echo "=== Starting Docker cleanup ==="
            docker images --format "{{.Repository}}:{{.Tag}} {{.ID}}" | \
              grep -v ":latest" | \
              awk '{print $2}' | \
              xargs -r docker rmi || true
            docker system prune -f
            echo "=== Cleanup completed ==="