.PHONY: all os stow deps claude claude-save

OS_NAME := $(shell uname -s | tr A-Z a-z)

CLAUDE_HISTORY_REPO := git@git.service:secstate/claude-history
CLAUDE_HISTORY_DIR  := $(HOME)/.claude-history
CLAUDE_HISTORY_PATHS := projects plans tasks history.jsonl

all: stow claude

stow:
	mkdir -p ~/.gnupg && chmod 0700 ~/.gnupg
	stow -t ~ */
	dconf load / < gnome/.local/share/custom-gconf.conf \

deps:
	@echo "Installing software for ${OS_NAME} platform"
	@if [ $(OS_NAME) = "darwin" ]; then\
		cd macos/.config/homebrew && brew bundle\
	fi
	@if [ $(OS_NAME) = "linux" ]; then\
		@echo "Not macos"\
	endif

os:
	@echo $(OS_NAME)

# Clone the private session-state repo and symlink it into ~/.claude so Claude
# Code resumes prior sessions. Sessions only match when the checkout path is
# identical to the one recorded in the project directory name.
claude:
	@test -d $(CLAUDE_HISTORY_DIR) || git clone $(CLAUDE_HISTORY_REPO) $(CLAUDE_HISTORY_DIR)
	@mkdir -p ~/.claude
	@for p in $(CLAUDE_HISTORY_PATHS); do \
		test -e $(CLAUDE_HISTORY_DIR)/$$p || continue; \
		test -L ~/.claude/$$p && continue; \
		if [ -e ~/.claude/$$p ]; then \
			echo "claude: ~/.claude/$$p exists and is not a symlink, leaving it alone"; \
			continue; \
		fi; \
		ln -s $(CLAUDE_HISTORY_DIR)/$$p ~/.claude/$$p; \
		echo "claude: linked $$p"; \
	done
	@if [ $(OS_NAME) = "linux" ]; then \
		systemctl --user daemon-reload && \
		systemctl --user enable --now claude-save.timer; \
	fi
	@if [ $(OS_NAME) = "darwin" ]; then \
		launchctl bootout gui/$$(id -u)/com.powellc.claude-save 2>/dev/null; \
		launchctl bootstrap gui/$$(id -u) ~/Library/LaunchAgents/com.powellc.claude-save.plist && \
		echo "claude: loaded com.powellc.claude-save"; \
	fi

claude-save:
	@cd $(CLAUDE_HISTORY_DIR) && \
		git add -A && \
		if git diff --cached --quiet; then \
			echo "claude-save: nothing to commit"; \
		else \
			git commit -qm "Sync session state" && echo "claude-save: committed"; \
		fi && \
		if git remote get-url origin >/dev/null 2>&1; then \
			git push -q && echo "claude-save: pushed"; \
		else \
			echo "claude-save: no origin remote, skipping push"; \
		fi
