# .DEFAULT_GOAL := build
# DEFAULT_TARGET = build
VERSION := "0.1.0"
TODAY = $(shell date +%Y%m%d)
RESTORE_DATE = ${TODAY}
ROOT_DIR:=$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
DC_EXEC = docker compose exec

ifneq ("$(wildcard ${ROOT_DIR}/.restore)","")
	include ${ROOT_DIR}/.restore
	export
endif

# .PHONY: build clean patch minor major fmt lint

clean: ## cleans repo
	-rm -rf dist
	-rm -rf env

patch: ## update patch version
	git aftermerge patch || exit 1

minor: ## updates minor version
	git aftermerge minor || exit 1

major: ## updates major version
	git aftermerge major || exit 1

help: ## Help menu for teammates
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "[36m%-20s[0m %s\n", $$1, $$2}' 

fmt: ## use black to fmt the code
	poetry run black .  || exit 1

lint: ## use flake8 to lint the code
	poetry run flake8 . || exit 1

test: clean fmt lint ## run clean, fmt, lint, and all the tests
	poetry run pytest || exit 1

build: test ## run test and run build
	poetry build

serve: ## Run the dev server
	${DC_EXEC} web python manage.py runserver

migrations: ## run makemigrations and migrate
	${DC_EXEC} web python manage.py makemigrations && ${DC_EXEC} web python manage.py migrate

flush: ## flush out all the data accrued
	${DC_EXEC} web python manage.py flush --no-input

user: ## create super user
	${DC_EXEC} web python manage.py createsuperuser

secretkey: ## generate a secret key
	poetry run python -c "import secrets; print(secrets.token_urlsafe())"

shell: ## start a django shell
	${DC_EXEC} web python manage.py shell

psql: ## start a psql session
	${DC_EXEC} db psql -U django

js: ## collect all the js and css
	${DC_EXEC} web python manage.py collectstatic --no-input

worker: ## start a celery worker
	poetry run celery -A webprj.celery_app worker -l INFO

up: ## start docker compose
	VERSION=$(VERSION) docker compose up -d --build

down: ## stop docker compose
	VERSION=$(VERSION) docker compose down

backup: down ## take a db backup 
	tar cvzf backups/${APPNAME}-${TODAY}.tar.gz docker-compose.yml postgressl deploy config data Makefile
	echo "RESTORE_DATE=${TODAY}" > .restore
	$(MAKE) up

restore: down ## run a db restore
	tar xvzf backups/${APPNAME}-${RESTORE_DATE}.tar.gz
	$(MAKE) up

requirements.txt: ## generate a requirements.txt from poetry
	poetry run pip freeze | cut -d"@" -f1 > requirements.txt

restart: ## restart the web server
	docker compose restart web

logs:
	docker compose logs -f
# Not setup yet
#deploy: build
#       poetry publish -r focus