name: Restart Docker Container on Production
run-name: ${{ gitea.actor }} is runs CD pipeline

on:
  pull_request:
    types: [ assigned, opened, synchronize, reopened, edited ]

jobs:
  build:
    runs-on: ubuntu-latest
    container: ghcr.io/catthehacker/ubuntu:act-latest    
    env:
      RUNNER_TOOL_CACHE: /toolcache
      IMAGE_NAME: rbl-news-webapp
      REGISTRY: git.wohlleben.dev
      REPO_OWNER: itob
    steps:
      - name: Check out repository code
        uses: actions/checkout@v4          
      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          registry: git.wohlleben.dev
          username: ${{ gitea.actor }}
          password: ${{ vars.REGISTRY_TOKEN }}
      - name: Build and push WebApp container image
        run: |
          TODAY=$(date +'%Y-%m-%d')
          docker build -t ${REGISTRY}/${REPO_OWNER}/${IMAGE_NAME}:${TODAY} -t ${REGISTRY}/${REPO_OWNER}/${IMAGE_NAME}:latest -f IaC/RBLNews.Web/Dockerfile .
          docker push ${REGISTRY}/${REPO_OWNER}/${IMAGE_NAME}:${TODAY}
          docker push ${REGISTRY}/${REPO_OWNER}/${IMAGE_NAME}:latest
      - name: Restart all Docker Container on Test Environment
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ vars.SRV02_DOCKER_VM_HOST_ADDRESS }}
          username: ${{ vars.SRV02_DOCKER_VM_USER_NAME }}
          key: ${{ vars.SRV02_DOCKER_VM_ROOT_USER_SSH_KEY }}
          script: |            
            docker pull git.wohlleben.dev/itob/rbl-news-webapp:latest
            docker stop rbl-news-webapp
            docker rm rbl-news-webapp
            docker run --init -d --name rbl-news-webapp -p 8000:8080 -e ASPNETCORE_ENVIRONMENT=Test --restart=always git.wohlleben.dev/itob/rbl-news-webapp:latest
            docker system prune -af