name: CI/CD Pipeline

on:
  push:
    branches:
      - master

jobs:
  build-and-deploy:
    runs-on: shell
    steps:
      - name: Clone repository
        run: git clone --depth 1 "http://192.168.8.174:3000/${GITHUB_REPOSITORY}.git" .
        env:
          GIT_TERMINAL_PROMPT: '0'

      - name: Ensure Docker CLI
        run: |
          apk add --no-cache docker-cli docker-cli-compose openssh-client || true
          grep -q '^vrubel:' /etc/passwd || echo 'vrubel:x:1000:1000::/data:/bin/sh' >> /etc/passwd

      - name: Setup .env for CI/CD
        run: cp .env.example .env

      - name: Build Docker image
        run: docker build -t 192.168.8.174:3000/vrubel/chess-calc:latest .

      - name: Test image
        run: |
          docker run -d --name chess-calc-test 192.168.8.174:3000/vrubel/chess-calc:latest sleep 30
          docker exec chess-calc-test python3 -c "from swiss_calc import parser; print('Module OK')"
          docker logs chess-calc-test
          docker rm -f chess-calc-test

      - name: Login to Gitea Container Registry
        run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login http://192.168.8.174:3000 -u "${{ secrets.REGISTRY_USER }}" --password-stdin

      - name: Push image to registry
        run: docker push 192.168.8.174:3000/vrubel/chess-calc:latest

      - name: Copy docker-compose to prod host
        run: scp -i /data/.ssh/id_ed25519 -o StrictHostKeyChecking=no docker-compose.prod.yml vrubel@192.168.8.171:~/services/ChessCalcNextTour/docker-compose.yml

      - name: Deploy on prod host
        run: ssh -i /data/.ssh/id_ed25519 -o StrictHostKeyChecking=no vrubel@192.168.8.171 "cd ~/services/ChessCalcNextTour && docker pull 192.168.8.174:3000/vrubel/chess-calc:latest && docker compose up -d --remove-orphans"
