name: Deploy
on:
  push:
    branches:
      - master

env:
  IMAGE_NAME: kopyl-dev-v2
  DOCKER_HUB_REGISTRY: git.radner.ru

jobs:
  build-and-publish:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository code
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          registry: ${{ env.DOCKER_HUB_REGISTRY }}
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: |
            ${{ env.DOCKER_HUB_REGISTRY }}/${{ secrets.DOCKER_USERNAME }}/${{ env.IMAGE_NAME }}:latest

  deploy:
    runs-on: ubuntu-latest
    needs: build-and-publish

    steps:
      - name: Set up SSH
        uses: webfactory/ssh-agent@v0.5.3
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}

      - name: Deploy to Remote Host
        env:
          REMOTE_USER: ${{ secrets.REMOTE_USER }}
          REMOTE_HOST: ${{ secrets.REMOTE_HOST }}
          IMAGE_NAME: ${{ env.IMAGE_NAME }}
          DOCKER_HUB_REGISTRY: ${{ env.DOCKER_HUB_REGISTRY }}
          DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
        run: |
          ssh_command="
            docker pull ${DOCKER_HUB_REGISTRY}/${DOCKER_USERNAME}/${IMAGE_NAME}:latest
            docker stop ${IMAGE_NAME} || true
            docker rm ${IMAGE_NAME} || true
            docker run -d --name ${IMAGE_NAME} -p 3006:3000 ${DOCKER_HUB_REGISTRY}/${DOCKER_USERNAME}/${IMAGE_NAME}:latest
          "
          ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "$ssh_command"
