#!/bin/sh
SERVICE="com.comfyui"
DIR="$HOME/Library/LaunchAgents"
FILE="$DIR/$SERVICE.plist"

detect_comfyui_dir() {
	for d in \
		"$HOME/ComfyUI" \
		"/Volumes/"*/ComfyUI
	do
		if [ -f "$d/main.py" ] && [ -d "$d/comfy" ]; then
			echo "$d"
			return 0
		fi
	done
	return 1
}

install() {
	MNT="${1:-$(detect_comfyui_dir)}"
	[ -n "$MNT" ] || { echo "ComfyUI directory not found. Specify it as an argument: $0 install /path/to/ComfyUI" >&2; exit 1; }

	mkdir -p "$DIR"
	cat > "$FILE" <<- EOF
	<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
	  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
	<plist version="1.0">
	<dict>
		<key>Label</key>
		<string>$SERVICE</string>

		<key>WorkingDirectory</key>
		<string>$MNT</string>

		<key>EnvironmentVariables</key>
		<dict>
			<key>PATH</key>
			<string>/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
		</dict>

		<key>ProgramArguments</key>
		<array>
			<string>/bin/sh</string>
			<string>-c</string>
			<string>cd "$MNT" && \
			  PYTHON_VER=3.13 && \
			  VENV=venv-mac-\$PYTHON_VER && \
			  OPTIONS="--enable-manager" && \
			  OPTIONS="\$OPTIONS --listen" && \
			  git pull --rebase && \
			  if [ -d \$VENV ]; then uv venv \$VENV -p \$PYTHON_VER --allow-existing; else uv venv \$VENV -p \$PYTHON_VER; fi && \
			  . \$VENV/bin/activate && \
			  uv pip install pip && \
			  pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cpu && \
			  pip install -r requirements.txt && \
			  pip install -r manager_requirements.txt && \
			  pip install matrix-nio && \
			  find custom_nodes -mindepth 1 -maxdepth 1 -type d | while read n; do \
			    [ -d "\$n" ] && (cd "\$n" && { [ -d .git ] && git pull --rebase; }; [ -r requirements.txt ] && pip install -r requirements.txt) || true; \
			  done && \
			  exec python main.py \$OPTIONS</string>
		</array>

		<key>RunAtLoad</key>
		<true/>

		<key>KeepAlive</key>
		<dict>
			<key>SuccessfulExit</key>
			<false/>
		</dict>

		<key>ThrottleInterval</key>
		<integer>10</integer>

		<key>StandardOutPath</key>
		<string>/tmp/comfyui.stdout.log</string>

		<key>StandardErrorPath</key>
		<string>/tmp/comfyui.stderr.log</string>
	</dict>
	</plist>
	EOF
	launchctl load "$FILE"
	launchctl start "$SERVICE"
	echo "installed and started $SERVICE"
	echo "logs: tail -f /tmp/comfyui.*.log"
}

uninstall() {
	launchctl stop "$SERVICE" 2>/dev/null || true
	launchctl unload "$FILE" 2>/dev/null || true
	rm -f "$FILE"
	echo "removed $SERVICE"
}

usage() {
	echo "usage: ${0##*/} [-h] [-u] [-l] [-p PATH]"
	echo "  -h  show this help"
	echo "  -u  disable and remove the launchd service"
	echo "  -l  show the service log"
	echo "  -p  path to ComfyUI directory (auto-detected if omitted)"
}

PATH_ARG=""
while getopts hulp: opt; do
	case $opt in
		h) usage; exit ;;
		u) uninstall; exit ;;
		l) tail -f /tmp/comfyui.stdout.log /tmp/comfyui.stderr.log; exit ;;
		p) PATH_ARG="$OPTARG" ;;
	esac
done
install "$PATH_ARG"
