name: Build and Deploy Jekyll

on:
  push:
    branches:
      - main
  workflow_dispatch:

env:
  IMAGE: registry.alocoq.fr/coqresearch:latest

jobs:
  deploy:
    runs-on: native
    timeout-minutes: 30

    steps:
      - name: Build and push image with Kaniko
        run: |
          cat <<'EOF' | kubectl apply -f -
          apiVersion: batch/v1
          kind: Job
          metadata:
            name: coqresearch-kaniko
            namespace: ci
          spec:
            backoffLimit: 0
            template:
              spec:
                restartPolicy: Never
                initContainers:
                  - name: prepare
                    image: ruby:3.3-alpine
                    command:
                      - sh
                      - -c
                      - |
                        set -eux
                        apk add --no-cache git build-base

                        git clone --depth 1 https://git.alocoq.fr/alois/CoqResearch.git /work
                        cd /work

                        bundle install
                        bundle exec jekyll build

                        mkdir -p /workspace/image
                        cp -a /work/_site/. /workspace/image/

                        cat > /workspace/Dockerfile <<'DOCKER'
                        FROM nginx:alpine
                        RUN rm -rf /usr/share/nginx/html/*
                        COPY image/ /usr/share/nginx/html/
                        DOCKER
          
                    volumeMounts:
                      - name: workspace
                        mountPath: /workspace

                containers:
                  - name: kaniko
                    image: gcr.io/kaniko-project/executor:debug
                    args:
                      - --context=dir:///workspace
                      - --dockerfile=/workspace/Dockerfile
                      - --destination=registry.alocoq.fr/coqresearch:latest
                    volumeMounts:
                      - name: workspace
                        mountPath: /workspace

                volumes:
                  - name: workspace
                    emptyDir: {}
          EOF

      - name: Wait for build
        run: |
          kubectl -n ci wait --for=condition=complete job/coqresearch-kaniko --timeout=1800s

      - name: Show logs
        if: always()
        run: |
          kubectl -n ci logs job/coqresearch-kaniko -c prepare || true
          kubectl -n ci logs job/coqresearch-kaniko -c kaniko || true

      - name: Deploy
        run: |
          kubectl -n research set image deployment/research-nginx \
            research-nginx=registry.alocoq.fr/coqresearch:latest

          kubectl -n research rollout restart deployment/research-nginx
          kubectl -n research rollout status deployment/research-nginx

      - name: Cleanup
        if: always()
        run: |
          kubectl -n ci delete job coqresearch-kaniko --ignore-not-found=true