SHELL:=/usr/bin/env bash
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Makefile
# NOTE: Do not change the contents of this file!
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

include .env

################################
# VARIABLES
################################

ARTEFACT_NAME:=${APPNAME}
ifeq ($(OS),Windows_NT)
ARTEFACT_NAME:=${APPNAME}.exe
endif

################################
# Macros
################################

define create_file_if_not_exists
	@touch "$(1)";
endef

define create_folder_if_not_exists
	@if ! [ -d "$(1)" ]; then mkdir "$(1)"; fi
endef

define delete_if_file_exists
	@if [ -f "$(1)" ]; then rm "$(1)"; fi
endef

define delete_if_folder_exists
	@if [ -d "$(1)" ]; then rm -rf "$(1)"; fi
endef

define clean_all_files
	@find . -type f -name "$(1)" -exec basename {} \;
	@find . -type f -name "$(1)" -exec rm {} \; 2> /dev/null
endef

define clean_all_folders
	@find . -type d -name "$(1)" -exec basename {} \;
	@find . -type d -name "$(1)" -exec rm -rf {} \; 2> /dev/null
endef

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# TARGETS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

################################
# BASIC TARGETS: setup, build, run
################################
setup: check-system-requirements setup-no-checks
setup-no-checks:
	@cargo update
build: check-system-requirements build-no-checks
build-no-checks:
	@$(call delete_if_file_exists,"dist/${ARTEFACT_NAME}")
	@#$(call delete_if_file_exists,"Cargo.lock")
	@cargo build --release
	@cp "target/release/${ARTEFACT_NAME}" "dist/"
run-precheck:
	@if ! [ -f "dist/${ARTEFACT_NAME}" ]; then \
		echo "No artefact found! Run `make build` first"; \
		exit 1; \
	fi
run:
	@make run-precheck
	@dist/${ARTEFACT_NAME};
all: setup build run
################################
# TARGETS: testing
################################
tests: unit-tests
unit-tests:
	cargo test
################################
# AUXILIARY (INTERNAL TARGETS)
################################
check-system-requirements:
	@if ! ( cargo version >> /dev/null 2> /dev/null ); then \
		echo "Install Rust cargo first."; \
		exit 1; \
	fi
	@cargo version
################################
# TARGETS: clean
################################
clean:
	@echo "All system artefacts will be force removed."
	@$(call clean_all_files,.DS_Store)
	@echo "All build artefacts will be force removed."
	@$(call clean_all_folders,target)
	@cargo clean
	@exit 0