# Makefile for Quarto Project Automation

# Detect OS
OS := $(shell uname | tr A-Z a-z)
ifeq ($(OS), darwin)
    OS := OSX
else ifeq ($(OS), linux)
    OS := linux
else
    $(error Unknown operating system)
endif

# Fetch Git branch and project details
branchname := $(shell git branch --show-current)
reponame := $(shell basename $(shell git rev-parse --show-toplevel))
projtype := $(shell basename $(shell dirname $(shell git rev-parse --show-toplevel)))
pubtype := $(if $(findstring PUB,$(branchname)),public,protected)
remotedir := drwater@serev:/home/www/drwater/$(projtype)/$(pubtype)/$(reponame)/@$(branchname)
outputdir := $(shell awk -F': *' '/^ *output-dir:/ {print $$2 "/" }' ./_quarto.yml)
siteurl := https://drwater.rcees.ac.cn/$(projtype)/$(pubtype)/$(reponame)/@$(branchname)


# Variables for colors and port
bcolor := grey
port := 4199

# Set background color based on branch name
ifeq ($(findstring R1,$(branchname)),R1)
    bcolor := orange
else ifeq ($(findstring R2,$(branchname)),R2)
    bcolor := lightblue
else ifeq ($(findstring R3,$(branchname)),R3)
    bcolor := lightgreen
else ifeq ($(findstring PUB,$(branchname)),PUB)
    bcolor := light
endif

# Set port based on branch name
branch_ports := main:4200 SM:4201 TX:4202 FJ:4203 YF:4204 ZY:4205 WW:4206 JB:4207 YY:4208
port := $(shell echo $(branch_ports) | tr " " "\n" | grep -E "^$(branchname):" | sed -E 's/^$(branchname):([0-9]+)/\1/')
port := $(if $(port),$(port),4199)

# Define the state file
STATE_FILE := .source_state

# checkfile
GREPSTR := " \|^submit\|^analysis\|_cache\|_freeze\|^site_libs\|^www"

# Default target
.PHONY: all preview readme rsync local clean upload fix_links force

all: render upload clean

# Render target with hash checking
render:
	@current_hash=$$(find $(shell git ls-files "*.qmd" "_*.yml" "*.pdf" "*.svg" "*.png" | grep -v $(GREPSTR)) -exec cat {} + | md5sum | awk '{print $$1}'); \
	if [ ! -f $(STATE_FILE) ] || [ "$$current_hash" != "$$(cat $(STATE_FILE))" ]; then \
		echo "Changes detected, rendering..."; \
		quarto render; \
		echo "$$current_hash" > $(STATE_FILE); \
		git add . && git commit -m "render compile"; \
	else \
		echo "No changes detected, skipping render."; \
	fi

# Force render target
force: 
	@echo "Forcing render..."
	@quarto render
	@current_hash=$$(find $(shell git ls-files "*.qmd" "_*.yml" "*.pdf" "*.svg" "*.png" | grep -v $(GREPSTR)) -exec cat {} + | md5sum | awk '{print $$1}'); \
	echo "$$current_hash" > $(STATE_FILE); \
	git add . && git commit -m "render compile"; \

# Preview the site on a specific port
preview:
	@quarto preview --port $(port)

# Generate README.md
readme:
	@quarto render index.qmd -t markdown -o README.md
	@sed -e '/^---/,/^---/d' "$(outputdir)/README.md" > README.md
	@rm "$(outputdir)/README.md"

# Sync files with remote server
rsync: render
	@rsync -azvu --progress --delete -r "$(outputdir)" "$(remotedir)"

# Open local site
local: render
	@if [ "$(OS)" = "OSX" ]; then open "$(outputdir)/index.html"; fi

# Clean unnecessary files
clean:
	@rm -f ./*.spl ./*.aux ./*.bbl ./*.blg ./*.log ./*.tex ./*.bcf ./*.tex.sedbak ./*.fdb_latexmk

# Upload files to server and fix links
upload: render
	@chmod -R 2775 "$(outputdir)"
	@$(MAKE) fix_links
	@if rsync -azvu --progress --delete -r "$(outputdir)" "$(remotedir)"; then \
		if [ "$(OS)" = "OSX" ]; then \
			open "$(siteurl)" 2>/dev/null; \
		fi; \
	else \
		echo "Rsync failed. Attempting alternative upload method..."; \
		mkdir -p "$(reponame)"; \
		rsync -azvu --progress --delete -r "$(reponame)" "$(dir $(remotedir))"; \
		rm -rf "$(reponame)"; \
		rsync -azvu --progress --delete -r "$(outputdir)" "$(remotedir)"; \
		if [ "$(OS)" = "OSX" ]; then \
			open "$(siteurl)" 2>/dev/null; \
		fi; \
	fi




# Fix links in www directory
fix_links:
	@find ./www -type f -name "*.html" -exec sed -i.bak \
		-e "s/{{< var branch >}}/$(branchname)/g" \
		-e "s/{{< var pubtype >}}/$(pubtype)/g" \
		-e "s/{{< var projtype >}}/$(projtype)/g" \
		-e "s/{{< var reponame >}}/$(reponame)/g" \
		-e "s/$(reponame)\/blob/$(reponame)\/raw\/branch/g" \
		-e "s/$(reponame)\/edit/$(reponame)\/_edit/g" {} +
	@find ./www -type f -name "*.bak" -exec rm {} +
