image: python:3.10-bullseye

stages:
  - build
  - deploy

variables:
  PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"

cache:
  paths:
    - .cache/pip
    - venv/

before_script:
  - python -V
  - pip install virtualenv
  - virtualenv venv
  - source venv/bin/activate
  - pip install -r requirements.txt
  - apt-get update && apt-get install -y jq  # Install jq

build-book:
  stage: build
  script:
    - |
      if [ "$CI_COMMIT_BRANCH" == "publish" ]; then
        echo "Building production version"
        teachbooks build --publish book/ > >(tee stdout.log) 2> >(tee stderr.log >&2)
      else
        echo "Building draft version"
        teachbooks build book/ > >(tee stdout.log) 2> >(tee stderr.log >&2)
      fi
  artifacts:
    paths:
      - book/_build/html
      - stdout.log
      - stderr.log
    expire_in: 1 week
  rules:
    - if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "publish"
    - if: $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "main" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "publish"
      when: always

deploy-draft:
  stage: deploy
  needs: ["build-book"]
  script:
    - |
      BUILD_JOB_ID=$(curl -s -H "PRIVATE-TOKEN: $CI_JOB_TOKEN" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/pipelines/${CI_PIPELINE_ID}/jobs?scope[]=success" | jq '.[] | select(.name=="build-book") | .id')
      curl -X POST https://mude.citg.tudelft.nl/hooks/book-deploy-draft \
        -H "Content-Type: application/json" \
        -H "X-Gitlab-Token: glpat-m4CzsDqHnXNn3Pf5Whyd" \
        -d '{
          "object_kind": "pipeline",
          "object_attributes": {
            "status": "success",
            "ref": "main"
          },
          "build_job_id": "'$BUILD_JOB_ID'"
        }'
  environment:
    name: draft
    url: https://mude.citg.tudelft.nl/2024/book/draft
  rules:
    - if: $CI_COMMIT_BRANCH == "main"

deploy-production:
  stage: deploy
  needs: ["build-book"]
  script:
    - |
      BUILD_JOB_ID=$(curl -s -H "PRIVATE-TOKEN: $CI_JOB_TOKEN" "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/pipelines/${CI_PIPELINE_ID}/jobs?scope[]=success" | jq '.[] | select(.name=="build-book") | .id')
      curl -X POST https://mude.citg.tudelft.nl/hooks/book-deploy-production \
        -H "Content-Type: application/json" \
        -H "X-Gitlab-Token: glpat-m4CzsDqHnXNn3Pf5Whyd" \
        -d '{
          "object_kind": "pipeline",
          "object_attributes": {
            "status": "success",
            "ref": "publish"
          },
          "build_job_id": "'$BUILD_JOB_ID'"
        }'
  environment:
    name: production
    url: https://mude.citg.tudelft.nl/2024/book
  rules:
    - if: $CI_COMMIT_BRANCH == "publish"