name: Gitea CI/CD

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Login to Docker registry
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
          registry: https://registry.rokoh.com

      - name: Build Docker image
        run: docker build . -t rokoh:latest -f rokoh/Dockerfile

      - name: Tag Docker image
        run: docker tag rokoh:latest registry.rokoh.com/rokoh:latest

      - name: Push Docker image to registry
        run: docker push registry.rokoh.com/rokoh:latest

      - name: SSH Deploy
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: 10.1.1.90
          username: ${{ secrets.SERVER_USERNAME }}
          password: ${{ secrets.SERVER_PASSWORD }}
          script: |
           if docker ps -a --format '{{.Names}}' | grep -q rokoh; then
             docker stop rokoh || true
             docker rm rokoh || true
             docker image rm rokoh:latest
           fi
             docker login registry.rokoh.com -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} && docker image pull registry.rokoh.com/rokoh:latest
             docker run -d -p 2000:80 --restart=always --name rokoh registry.rokoh.com/rokoh
             docker image prune -f

      - name: Prune Docker resources
        run: docker system prune -af --volumes