# Makefile for Quarto Project Automation
# Detect OS
HOSTNAME := $(shell hostname)
OS := $(shell uname | tr A-Z a-z)
ifeq ($(OS), darwin)
    SEDI := sed -i ''
    OS := OSX
else ifeq ($(OS), linux)
    SEDI := sed -i
    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 := dwuser@drwater.net:/home/www/drc/$(projtype)/$(pubtype)/$(reponame)/$(branchname)
outputdir := $(shell awk -F': *' '/^ *output-dir:/ {print $$2 "/" }' ./_quarto.yml)
siteurl := https://drc.drwater.net/$(projtype)/$(pubtype)/$(reponame)/$(branchname)

branchnames := "TX\|FJ\|YF\|ZY\|WW\|JB\|YY\|YJ\|DYF"

# 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 YJ:4209 DYF:4210
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 check_git_status

all: local upload clean commit push
	
force: updrefbib check_git_status updvariable render

local: updrefbib check_git_status updvariable lazyrender

updmakefile:
	@if [ "$(OS)" = "OSX" ] && [ "$(HOSTNAME)" = "max" ]; then \
		echo "基于 $$HOME/bin/publish2dw.Makefile 更新本项目 Makefile..."; \
		cp "$$HOME/bin/publish2dw.Makefile" "./Makefile"; \
		git add "Makefile" && git commit -m "Update Makefile"; \
		echo "本项目Makefile更新完成."; \
	else \
		echo "Makefile 无需在本系统上更新."; \
	fi


updrefbib:
	@if [ "$(OS)" = "OSX" ] && [ "$(HOSTNAME)" = "max" ]; then \
		echo "更新本项目参考文献..."; \
		cp "$$HOME/literature/Ref.bib" "./BB/"; \
		echo "推送本地参考文献到远程服务器..."; \
		rsync -azvu --progress "$$HOME/literature/Ref.bib" "drwater.net:/home/www/drc/datapool/public/BB/Ref.bib"; \
		echo "本项目参考文献更新完成."; \
	else \
	  echo "检查网络连通性..."; \
		if ping -c 1 -W 1 drc.drwater.net > /dev/null 2>&1; then \
			echo "网络正常,更新本项目参考文献..."; \
			wget -O BB/Ref.bib "https://drc.drwater.net/datapool/public/BB/Ref.bib"; \
			echo "本项目参考文献更新完成."; \
		else \
			echo "网络不可用,跳过参考文献更新."; \
		fi; \
	fi; \
	git add BB/Ref.bib; \
	if [ "$$(git diff --cached)" ]; then \
		git commit -m "Update Ref.bib"; \
	fi

check_git_status:
	@uncommitted=$$(git status --porcelain); \
	if [ -n "$$uncommitted" ]; then \
	  git status; \
		read -p "当前存在未提交的修改(如上),是否要提交?(Y/N, default is N): " answer; \
		answer=$${answer:-N}; \
		if [ "$$answer" = "Y" ] || [ "$$answer" = "y" ]; then \
			read -p "请输入修改说明: " message; \
			git add . && git commit -m "$$message"; \
		else \
			echo "未提交,如后续操作为pull,则无法继续"; \
		fi; \
	fi



# Lazy render with hash checking
lazyrender:
	@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 "源文件发生变化, 重新编译..."; \
		echo "$$current_hash" > $(STATE_FILE); \
		$(MAKE) render; \
	else \
		echo "源文件无变化, 跳过编译..."; \
		exit 0; \
	fi

# Render target
render:
	@quarto render

commit:
	@echo "提交修改(commit)..."; \
		git add .; \
		if [ -n "$$(git diff --cached)" ]; then \
		git commit -m "render compile"; \
		else \
		echo "没有修改记录,跳过."; \
		fi; \

# Pull changes from the specified branch based on the current branch
pull:
	@echo "从远程拉取项目更新..."; \
		$(MAKE) check_git_status; \
		git pull; \
		current_branch=$$(git rev-parse --abbrev-ref HEAD); \
		if [ "$$current_branch" = main ]; then \
		  echo "当前分枝为$$current_branch."; \
			remote_branch=$$(git branch --remote | grep -v 'main' | grep $(branchnames) | awk '{print $$1}' | sed 's/origin\///' | head -n 1); \
			if [ -n "$$remote_branch" ]; then \
		    echo "尝试从远程分枝$$remote_branch 拉取更新..."; \
				git pull --rebase origin $$remote_branch; \
			else \
				echo "远程无可用分支$$remote_branch."; \
			fi; \
			else \
			echo "尝试将远程main分枝合并至本地$$current_branch 分枝."; \
			git pull --rebase origin main; \
		fi

# Pull changes from the main branch
pullmain:
	$(MAKE) check_git_status; \
		@current_branch=$$(git rev-parse --abbrev-ref HEAD); \
		@echo "尝试将远程main分枝合并至本地$$current_branch 分枝."; \
		git pull --rebase origin main; \

push:
	@echo "推送到远程..."; \
		git push

filehash:
	@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)

# 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:
	@rsync -azvu --progress --delete -r "$(outputdir)" "$(remotedir)"

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

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

# Upload files to server and fix links
upload: backupdocx
	@mkdir -p "$(outputdir)" && 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

backupdocx:
	@echo "备份MS.docx文件..."; \
	currentcommithash=$$(git rev-parse --short HEAD); \
	datetime=$$(git show -s --format=%ci $$currentcommithash | sed 's/[-: ]//g' | cut -c3-12); \
	mkdir -p TC/MS/; \
	existing_file=$$(find TC/MS -name "MS*.docx" -exec cmp -s www/MS/MS.docx {} \; -print -quit); \
	if [ -n "$$existing_file" ]; then \
		echo "与www/MS/MS.docx 内容相同的备份文件已存在: $$existing_file"; \
		echo "无需备份."; \
	else \
		if [ ! -e TC/MS/MS$${datetime}_$${currentcommithash}.docx ]; then \
			cp www/MS/MS.docx TC/MS/MS$${datetime}_$${currentcommithash}.docx; \
			echo "备份TC/MS/MS$${datetime}_$${currentcommithash}.docx完成."; \
			git add TC/MS/MS$${datetime}_$${currentcommithash}.docx; \
			if [ "$$(git diff --cached)" ]; then \
				git commit -m "备份TC/MS/MS$${datetime}_$${currentcommithash}.docx"; \
			fi; \
		else \
			echo "TC/MS/MS$${datetime}_$${currentcommithash}.docx已存在,无需备份."; \
		fi; \
	fi;


trackchange:
	@if [ "$(projtype)" != "manuscript" ]; then \
	exit 0; \
	fi; \
	echo "选择两个提交以比较文档..."; \
	hashes=$$(git log --pretty=format:'%h: %s BY %an (%ar)' \
	| grep -E "$$(ls TC/MS/*.docx | xargs -n1 basename | sed -E 's/MS.*_([0-9a-f]+)\.docx/\1/' | tr '\n' '|')SMT_】" \
	| fzf --multi --reverse --preview="echo {}" ); \
	echo $$hashes; \
	hash1=$$(echo $$hashes | sed -e 's/) \([a-z0-9]\{7\}:\)/)\n\1/g' | tail -n 1 | awk '{print $$1}' | tr -d ':'); \
	hash1=$$(git rev-parse --short $${hash1}^); \
	datetime1=$$(git show -s --format=%ci $$hash1 | sed 's/[-: ]//g' | cut -c3-12); \
	hash2=$$(echo $$hashes | sed -e 's/) \([a-z0-9]\{7\}:\)/)\n\1/g' | head -n 1 | awk '{print $$1}' | tr -d ':'); \
	hash2=$$(git rev-parse --short $${hash2}^); \
	datetime2=$$(git show -s --format=%ci $$hash2 | sed 's/[-: ]//g' | cut -c3-12); \
	if [ -z "$$hash1" ] || [ -z "$$hash2" ]; then \
	echo "必须选择两个提交."; \
	exit 1; \
	fi; \
	doc1="TC/MS/MS$${datetime1}_$$hash1.docx"; \
	echo "$$doc1"; \
	doc2="TC/MS/MS$${datetime2}_$$hash2.docx"; \
	echo "$$doc2"; \
	if [ -f "$$doc1" ] && [ -f "$$doc2" ] && [ "$$doc1" != "$$doc2" ]; then \
	echo "打开文件: $$doc1 和 $$doc2"; \
	open "$$doc1" "$$doc2"; \
	printf "MS$${datetime1}-$${datetime2}_$${hash1}-$${hash2}" | pbcopy; \
	echo "请在word中对比两个版本形成带修改痕迹的版本,并保存至TC/MS$${datetime1}-$${datetime2}_$${hash1}-$${hash2}.docx!"; \
	else \
	echo "一个或两个文件不存在: $$doc1, $$doc2"; \
	exit 1; \
	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 {} +

updvariable:
	@touch _variables.yml  # 如果文件不存在则创建
	@grep -q '^reponame:' _variables.yml || echo "reponame: $(reponame)" >> _variables.yml
	@if grep -q '^reponame:' _variables.yml; then \
		$(SEDI) 's/^reponame:.*/reponame: $(reponame)/' _variables.yml; \
	else \
		echo "reponame: $(reponame)" >> _variables.yml; \
	fi
	@grep -q '^projtype:' _variables.yml || echo "projtype: $(projtype)" >> _variables.yml
	@if grep -q '^projtype:' _variables.yml; then \
		$(SEDI) 's/^projtype:.*/projtype: $(projtype)/' _variables.yml; \
	else \
		echo "projtype: $(projtype)" >> _variables.yml; \
	fi
	@grep -q '^branch:' _variables.yml || echo "branch: $(branchname)" >> _variables.yml
	@if grep -q '^branch:' _variables.yml; then \
		$(SEDI) 's/^branch:.*/branch: $(branchname)/' _variables.yml; \
	else \
		echo "branch: $(branchname)" >> _variables.yml; \
	fi
	@grep -q '^pubtype:' _variables.yml || echo "pubtype: $(pubtype)" >> _variables.yml
	@if grep -q '^pubtype:' _variables.yml; then \
		$(SEDI) 's/^pubtype:.*/pubtype: $(pubtype)/' _variables.yml; \
	else \
		echo "pubtype: $(pubtype)" >> _variables.yml; \
	fi
	@grep -q '^nwAB:' _variables.yml || echo "nwAB: $(nwAB)" >> _variables.yml
	@if grep -q '^nwAB:' _variables.yml; then \
		$(SEDI) 's/^nwAB:.*/nwAB: $(nwAB)/' _variables.yml; \
	else \
		echo "nwAB: $(nwAB)" >> _variables.yml; \
	fi
	@grep -q '^nwMS:' _variables.yml || echo "nwMS: $(nwMS)" >> _variables.yml
	@if grep -q '^nwMS:' _variables.yml; then \
		$(SEDI) 's/^nwMS:.*/nwMS: $(nwMS)/' _variables.yml; \
	else \
		echo "nwMS: $(nwMS)" >> _variables.yml; \
	fi
	@grep -q '^figtblMS:' _variables.yml || echo "figtblMS: $(figtblMS)" >> _variables.yml
	@if grep -q '^figtblMS:' _variables.yml; then \
		$(SEDI) 's/^figtblMS:.*/figtblMS: $(figtblMS)/' _variables.yml; \
	else \
		echo "figtblMS: $(figtblMS)" >> _variables.yml; \
	fi
	@grep -q '^figtblSM:' _variables.yml || echo "figtblSM: $(figtblSM)" >> _variables.yml
	@if grep -q '^figtblSM:' _variables.yml; then \
		$(SEDI) 's/^figtblSM:.*/figtblSM: $(figtblSM)/' _variables.yml; \
	else \
		echo "figtblSM: $(figtblSM)" >> _variables.yml; \
	fi
	@mkpapervar


# Help: list all available commands with descriptions (English and Chinese)
help:
	@echo "Makefile for Quarto Project Automation"
	@echo "======================================="
	@echo "Available targets (English):"
	@echo ""
	@echo "  make all           - Execute local build, upload, clean, and commit"
	@echo "  make force         - Force render, hash update, upload, clean, and commit"
	@echo "  make local         - Check git status and perform a lazy render if changes detected"
	@echo "  make check_git_status - Check for uncommitted changes and ask to commit them"
	@echo "  make lazyrender    - Render if source files have changed based on hash comparison"
	@echo "  make render        - Force Quarto to render the project"
	@echo "  make commit        - Commit changes if no previous uncommitted changes"
	@echo "  make filehash      - Generate and store the file hash of source files"
	@echo "  make preview       - Preview the site locally on the specific port (default: 4199)"
	@echo "  make readme        - Render README.md from Quarto index.qmd"
	@echo "  make rsync         - Sync output files with the remote server"
	@echo "  make open          - Open the generated site locally in the browser"
	@echo "  make clean         - Clean up unnecessary files"
	@echo "  make upload        - Upload files to the server and fix links"
	@echo "  make fix_links     - Fix HTML links in the 'www' directory for the remote server"
	@echo "  make updmakefile   - Update the Makefile"
	@echo "  make help          - Display this help message"
	@echo ""
	@echo "Available targets (中文):"
	@echo ""
	@echo "  make all           - 执行本地构建、上传、清理和提交"
	@echo "  make force         - 强制渲染、更新哈希、上传、清理并提交"
	@echo "  make local         - 检查Git状态,若检测到更改则进行懒惰渲染"
	@echo "  make check_git_status - 检查未提交的更改,并询问是否提交"
	@echo "  make lazyrender    - 如果源文件发生更改,则根据哈希比较进行渲染"
	@echo "  make render        - 强制 Quarto 渲染项目"
	@echo "  make commit        - 如果没有未提交的更改则提交"
	@echo "  make filehash      - 生成并存储源文件的哈希值"
	@echo "  make preview       - 本地在特定端口预览网站 (默认: 4199)"
	@echo "  make readme        - 从 Quarto 的 index.qmd 生成 README.md"
	@echo "  make rsync         - 将输出文件同步到远程服务器"
	@echo "  make open          - 在浏览器中打开生成的网站"
	@echo "  make clean         - 清理不必要的文件"
	@echo "  make upload        - 上传文件到服务器并修复链接"
	@echo "  make fix_links     - 修复 'www' 目录中的 HTML 链接"
	@echo "  make updmakefile   - 更新本项目 Makefile"
	@echo "  make help          - 显示此帮助信息"
	@echo ""
	@echo "Environment variables (English and 中文):"
	@echo "  bcolor             - Background color based on branch name (基于分支名的背景颜色)"
	@echo "  port               - Port number based on branch name (基于分支名的端口号)"
	@echo "  STATE_FILE         - File for storing hash state of source files (用于存储源文件哈希状态的文件)"
	@echo "  siteurl            - The URL where the site will be hosted (网站托管的 URL)"
	@echo ""