name: Deploy to LXC

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:

jobs:
  deploy:
    name: Deploy to 192.168.40.22
    runs-on: ubuntu-latest
    if: github.repository_owner == 'PLACEHOLDER' # TODO: change after repo created

    steps:
      - uses: actions/checkout@v4

      - name: Set up SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.LXC_SSH_KEY }}" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -H ${{ secrets.LXC_HOST }} >> ~/.ssh/known_hosts

      - name: Build Docker image
        run: |
          docker build -t website-tuvi:${{ github.sha }} .
          docker save website-tuvi:${{ github.sha }} | gzip > image.tar.gz

      - name: Copy to LXC
        run: |
          scp image.tar.gz root@${{ secrets.LXC_HOST }}:/opt/website-tuvi/
          scp docker-compose.prod.yml root@${{ secrets.LXC_HOST }}:/opt/website-tuvi/

      - name: Load image + restart on LXC
        run: |
          ssh root@${{ secrets.LXC_HOST }} <<'EOF'
            cd /opt/website-tuvi
            gunzip -f image.tar.gz
            docker load -i image.tar
            docker tag website-tuvi:${{ github.sha }} website-tuvi:latest
            docker compose -f docker-compose.prod.yml up -d
            docker image prune -f
          EOF

      - name: Health check
        run: |
          for i in {1..30}; do
            if curl -fsS http://${{ secrets.LXC_HOST }}/api/health; then
              echo "Deploy OK"
              exit 0
            fi
            sleep 2
          done
          echo "Deploy health check failed"
          exit 1
