#######################################################################
#                            Main targets                             #
#######################################################################

## CASAnova on Wine in Docker

help: ## Show this help.
	@egrep -h '(\s##\s|^##\s)' $(MAKEFILE_LIST) | egrep -v '^--' | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[32m  %-35s\033[0m %s\n", $$1, $$2}'

INSTALLER_URL = https://web.archive.org/web/20070611110850fw_/http://nesa1.uni-siegen.de/softlab/download/CASAnova_Setup.exe

download_setup_exe: ## Downloads installer if missing
	@[ -f CASAnova_Setup.exe ] || { echo "${green}Downloading CASAnova_Setup.exe...${no_color}"; wget "$(INSTALLER_URL)" -O CASAnova_Setup.exe; }
	@[ -f CASAnova_Setup.exe ] && [ $$(stat -c%s CASAnova_Setup.exe) -gt 1000000 ] \
		|| { echo "${red}CASAnova_Setup.exe missing or too small (download failed?)${no_color}"; rm -f CASAnova_Setup.exe; exit 1; }

build: download_setup_exe ## Build the Docker image (downloads installer if missing).
	@echo "${green}Building image...${no_color}"
	docker compose build

up: ## Start the container.
	@echo "${green}Starting container...${no_color}"
	docker compose up --detach

down: ## Stop and remove the container.
	@echo "${green}Stopping container...${no_color}"
	docker compose down

status: ## Show current container status.
	@docker compose ps --all | \
		sed "s/\b\(exited\)\b/${orange}\U\1\E${no_color}/gi" | \
		sed "s/\b\(up\)\b/${green}\U\1\E${no_color}/gi" | \
		sed "s/\b\(healthy\)\b/${green}\U\1\E${no_color}/gi" | \
		sed "s/\b\(unhealthy\)\b/${orange}\U\1\E${no_color}/gi" | tee /tmp/status
	@(grep -qi "UP" /tmp/status && echo "${green}UP!${no_color}") || echo "${red}DOWN!${no_color}"

logs: ## Follow container logs.
	@echo "${green}Showing logs...${no_color}"
	docker compose logs --follow

prune: ## Remove dangling images for this project and unused build cache (cache is system-wide).
	docker image prune --filter "label=com.docker.compose.project=casanova_online" -f
	docker builder prune -f

.PHONY: help setup build up down status logs prune

green=`tput setaf 2`
orange=`tput setaf 9`
red=`tput setaf 1`
no_color=`tput sgr0`
