#!/usr/bin/env make

# customization points via makefile key-value arguments
#
# interpreter in images: 3.{6,7,8} currently available
# DOCKER_BASE_PYTHON=3.7
# test script executed with `docker_test`: mpi, notebooks_dir, oldest, vanilla, mpi, numpy_git, pip_installed
# GDT_TEST_SCRIPT=vanilla
# version pinned mirror to be used: stable or oldest
# PYPI_MIRROR=stable
# wheel check OS: debian_buster centos_8 debian_testing
# GDT_TEST_OS=debian_buster
# hypothesis profiles: dev, debug, ci, ci-pr, ci-large
# GDT_HYPOTHESIS_PROFILE=dev
# extra options to be passed to pytest
# GDT_PYTEST_EXTRA="--lf"

THIS_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
DOCKER_RUN=docker run -v $(THIS_DIR):/tutorials --env-file  $(THIS_DIR)/.env
CI_COMMIT_REF_NAME?=$(shell git rev-parse --abbrev-ref HEAD)
DOCKER_COMPOSE=CI_COMMIT_SHA=$(shell git log -1 --pretty=format:"%H") \
  	CI_COMMIT_REF_NAME=$(CI_COMMIT_REF_NAME) \
	NB_USER=$(NB_USER) $(COMPOSE_SUDO) docker-compose -f .binder/docker-compose.yml -p pymor
NB_DIR=tutorials/source
NB_USER:=${USER}
ifeq ($(GDT_SUDO), 1)
	COMPOSE_SUDO:=sudo -E
else
	COMPOSE_SUDO:=
endif

# this loads $(ENV_FILE) as both makefile variables and into shell env
ENV_FILE?=.env
include $(ENV_FILE)
export $(shell sed 's/=.*//' $(ENV_FILE))

.PHONY: docker_image test docs tutorials

docker_docs: docker_image
	NB_DIR=notebooks $(DOCKER_COMPOSE) run docs ./.ci/gitlab/test_docs.bash

tutorials:
	PYTHONPATH=${PWD}/src/:${PYTHONPATH} make -C tutorials html

# just a backward-compat alias
docs: tutorials

docker_image:
	$(DOCKER_COMPOSE) build

docker_run: docker_image
	$(DOCKER_COMPOSE) run --service-ports jupyter bash

docker_exec: docker_image
	$(DOCKER_COMPOSE) run --service-ports jupyter bash -l -c "${DOCKER_CMD}"

docker_tutorials: NB_DIR=tutorials/_build/html
docker_tutorials: docker_docs docker_jupyter

docker_test: docker_image
	GDT_TEST_SCRIPT=$(GDT_TEST_SCRIPT) $(DOCKER_COMPOSE) up pytest

docker_jupyter: docker_image
	NB_DIR=$(NB_DIR) $(DOCKER_COMPOSE) up jupyter
docker_wheel_check: docker_image
	GDT_TEST_OS=$(GDT_TEST_OS) $(DOCKER_COMPOSE) run --service-ports wheel_check bash
docker_install_check: docker_image
	GDT_TEST_OS=$(GDT_TEST_OS) $(DOCKER_COMPOSE) run --service-ports install_check bash

template:
	@./.ci/gitlab/template.ci.py ${GITLAB_TOKEN}
	@echo Files changed:
	@git diff --name-only

# docker targets
docker_template:
	@$(DOCKER_RUN) pymor/ci_sanity:$(CI_IMAGE_TAG) /tutorials/.ci/gitlab/template.ci.py ${GITLAB_TOKEN} \
	  || $(DOCKER_RUN) pymor/ci_sanity:latest /tutorials/.ci/gitlab/template.ci.py ${GITLAB_TOKEN}
