# Add any tasks that are not dependent on files to the .PHONY list.
.PHONY: clean dev_env dev \
	check_airflow_home docker_down \
	lint test test_unit \
	unit_lint_job \
	pip_lock_versions

clean:
	rm -rf \
		env \
		logs \
		airflow.cfg \
		airflow.db \
		coverage.xml \
		pyunit.xml \
		unittests.cfg \
		.pytest_cache \
		.coverage
	find . | grep -E '__pycache__|\.pyc|\.pyo$\' | xargs rm -rf

dev_env: env
	if [ ! -f env/bin/py.test ]; then env/bin/python -m pip install --use-pep517 -q -I -r requirements-dev.txt; fi

dev:
	mkdir logs || true
	docker compose -f docker-compose.dev.yaml up -d airflow-postgres
	docker compose -f docker-compose.dev.yaml up -d airflow-scheduler
	sleep 10
	docker compose -f docker-compose.dev.yaml up -d airflow-webserver

docker_down:
	docker compose down --remove-orphans

docker_dev_build:
	docker compose -f docker-compose.dev.yaml build

env:
	python3.11 -m venv env
	env/bin/python -m pip install -q -U pip setuptools wheel supervisor
	env/bin/python -m pip install --use-pep517 -q -I -r requirements.txt

lint: dev_env
	env/bin/python -m flake8 dags/ tests/ generate_fernet_key.py

airflow.db:
	AIRFLOW_HOME=`pwd` env/bin/airflow db init

test: airflow.db dev_env
	AIRFLOW_HOME=`pwd` env/bin/python -m pytest tests \
		--cov dags \
		--cov-report term-missing

check_airflow_home:
ifndef AIRFLOW_HOME
	$(error AIRFLOW_HOME is undefined)
endif

test_unit: check_airflow_home dev_env
	env/bin/airflow db init
	env/bin/python -m pytest tests \
		--cov=dags \
		--cov-report xml \
		--junitxml=pyunit.xml

docker_unit_lint:
	docker compose -f docker-compose.test.yaml up \
		--build \
		--exit-code-from airflow-lint-unit \
		--abort-on-container-exit \
		--remove-orphans \
		airflow-lint-unit

pip_lock_versions: clean
	python3.11 -m venv env
	env/bin/python -m pip install -q -U pip setuptools wheel
	env/bin/python -m pip install -q -I -r requirements-to-freeze.txt
	echo "-i https://pypi.theorchard.io/pypi/" > requirements.txt
	env/bin/python -m pip freeze >> requirements.txt
	env/bin/python -m pip install -q -r requirements-dev.txt

unit_lint_job: docker_unit_lint

down_unit_lint:
	docker compose down 

ci_unit_lint: ci_unit_lint_clean
	mkdir -p build
	chmod a+w build
	make docker_unit_lint

ci_unit_lint_clean: down_unit_lint
	rm -rf build

docker_test_integration:
	docker compose up \
		--build \
		--exit-code-from test-integration \
		--abort-on-container-exit \
		--remove-orphans \
		test-integration

ci_test_integration: docker_test_integration

docker_login:
	aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 086679231553.dkr.ecr.us-east-1.amazonaws.com
