PWD             := $(shell pwd)

ADMIN           := $(PWD)/admin
SUPPORT         := $(PWD)/support
CODEGEN         := $(PWD)/codegen/src/main

NICENESS        := 19
CONFIGURATION   := Release

DOTNET_RESTORE  :=
DOTNET_BUILD    :=
DOTNET_TEST     :=

AWK             := awk
FIND            := find
RM              := rm -f -r
SORT            := sort
XARGS           := xargs

PWSH            := pwsh
NICE             = nice -n $(NICENESS)
DOTNET           = $(NICE) $(SUPPORT)/dotnet_wrapper.sh
FSI              = $(DOTNET) fsi

TOOL_PKGS       := $(shell \
	$(FIND) $(PWD) -iname "Gdmt\.*\.fsproj" \
	| $(AWK) -F '/' '{ sub(/\.fsproj/, "", $$NF); if ($$NF != "Gdmt.Shared") print $$NF }' \
	| $(SORT))

.PHONY: all
all:
	$(MAKE) pack

.PHONY: clean
clean:
	$(FIND) $(PWD) -type d -iname ".cache" -exec $(RM) {} +
	-$(DOTNET) clean --verbosity quiet

.PHONY: build
build:
	$(DOTNET) msbuild "/t:PrintEnvironmentVariable_DOTNET_PKG_COMPAT"
	$(DOTNET) restore $(DOTNET_RESTORE) --force-evaluate
	$(DOTNET) build $(DOTNET_BUILD) --configuration $(CONFIGURATION) --no-restore

.PHONY: test
test:
	$(DOTNET) test $(DOTNET_TEST) --configuration $(CONFIGURATION)

.PHONY: pack
pack: build
pack:
	$(DOTNET) pack --configuration $(CONFIGURATION)

.PHONY: install
install: pack
install:
	echo $(TOOL_PKGS) | $(XARGS) -n 1 $(SUPPORT)/install_tool.sh

.PHONY: uninstall
uninstall:
	echo $(TOOL_PKGS) | $(XARGS) -n 1 $(SUPPORT)/uninstall_tool.sh

.PHONY: reinstall
reinstall: pack
reinstall:
	echo $(TOOL_PKGS) | $(XARGS) -n 1 $(SUPPORT)/reinstall_tool.sh

# TODO: Rewrite this sub-script in F#.
.PHONY: create-tools-list
create-tools-list:
	$(PWSH) $(CODEGEN)/powershell/Codegen/Scripts/create_tools_list.ps1

.PHONY: create-source
create-source:
	$(FSI) $(CODEGEN)/fsharp/Codegen/Scripts/create_license_mapping_fs.fsx
	$(FSI) $(CODEGEN)/fsharp/Codegen/Scripts/create_subcommands_fs.fsx

.PHONY: regen-source
regen-source: create-tools-list
regen-source: create-source
