#!/usr/bin/env bash
set -uo pipefail

VERSION="0.2.0"
SKILLS_FILE="${SKILLS_FILE:-$HOME/.config/skills}"
HARNESSES_FILE="${HARNESSES_FILE:-$HOME/.config/harnesses}"
LOCK_FILE="${SKILLS_AUTOUPDATE_LOCK:-${XDG_CACHE_HOME:-$HOME/.cache}/skills-autoupdate.lock}"
CACHE_DIR="${SKILLS_AUTOUPDATE_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/skills-autoupdate}"
MARKER=".skills-autoupdate"
LINE_RE='^([^{}=>[:space:]]+)(\{([^{}[:space:]]*)\})?(>=|>|=)?([^[:space:]]*)$'

export GIT_TERMINAL_PROMPT=0
export GIT_ASKPASS=/bin/true
export GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-ssh -o BatchMode=yes}"

failures=0

usage() {
	cat <<EOF
Usage: skills-autoupdate [-h] [-V]

Keeps the skills listed in $SKILLS_FILE up to date, via git,
in the skills folder of every harness listed in $HARNESSES_FILE.

Environment:
  SKILLS_FILE     list of skills (default ~/.config/skills)
  HARNESSES_FILE  list of harnesses (default ~/.config/harnesses)
  SKILLS_AUTOUPDATE_CACHE
                  mirrors of repositories with skills in subfolders
                  (default ~/.cache/skills-autoupdate)
EOF
}

log() {
	printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"
}

warn() {
	log "WARN $*"
}

fail() {
	log "ERROR $*"
	failures=$((failures + 1))
}

expand_path() {
	local p="$1"
	case "$p" in
		\~) p="$HOME" ;;
		\~/*) p="$HOME/${p:2}" ;;
		/*) ;;
		*) p="$HOME/$p" ;;
	esac
	printf '%s\n' "${p%/}"
}

default_root() {
	case "$1" in
		claude) printf '%s\n' "$HOME/.claude" ;;
		codex) printf '%s\n' "$HOME/.codex" ;;
		opencode) printf '%s\n' "${XDG_CONFIG_HOME:-$HOME/.config}/opencode" ;;
		antigravity) printf '%s\n' "$HOME/.gemini/antigravity" ;;
		pi) printf '%s\n' "$HOME/.pi/agent" ;;
		cursor) printf '%s\n' "$HOME/.cursor" ;;
		kimi) printf '%s\n' "$HOME/.kimi" ;;
		zcode) printf '%s\n' "$HOME/.zcode" ;;
		*) return 1 ;;
	esac
}

normalize_name() {
	case "$1" in
		claude | claude-code | claudecode) echo claude ;;
		codex | openai-codex) echo codex ;;
		opencode) echo opencode ;;
		antigravity | agy | gemini-antigravity) echo antigravity ;;
		pi | pi-agent | pi-coding-agent) echo pi ;;
		cursor | cursor-agent) echo cursor ;;
		kimi | kimi-cli) echo kimi ;;
		zcode | z-code | glm) echo zcode ;;
		*) return 1 ;;
	esac
}

detect_harness() {
	local d="$1" base
	[ -f "$d/opencode.json" ] || [ -f "$d/opencode.jsonc" ] && { echo opencode; return 0; }
	[ -f "$d/kimi.json" ] && { echo kimi; return 0; }
	[ -d "$d/cli/plugins" ] && [ -d "$d/workspace" ] && { echo zcode; return 0; }
	[ -f "$d/cli/config.json" ] && [ -d "$d/v2" ] && { echo zcode; return 0; }
	[ -f "$d/.credentials.json" ] || [ -f "$d/CLAUDE.md" ] || [ -f "$d/.claude.json" ] && { echo claude; return 0; }
	[ -f "$d/config.toml" ] && { [ -f "$d/AGENTS.md" ] || [ -f "$d/auth.json" ] || [ -f "$d/installation_id" ] || [ -d "$d/sessions" ]; } && { echo codex; return 0; }
	[ -f "$d/mcp_config.json" ] || [ -d "$d/brain" ] && { echo antigravity; return 0; }
	[ -f "$d/models.json" ] && [ -f "$d/settings.json" ] && { echo pi; return 0; }
	[ -f "$d/argv.json" ] || [ -f "$d/cli-config.json" ] || [ -f "$d/ide_state.json" ] && { echo cursor; return 0; }
	[ -d "$d/projects" ] && [ -f "$d/settings.json" ] && { echo claude; return 0; }
	base="$(basename "$d" | tr '[:upper:]' '[:lower:]')"
	case "$d" in
		*/.pi/agent) echo pi; return 0 ;;
		*/antigravity*) echo antigravity; return 0 ;;
	esac
	local h
	for h in opencode antigravity claude codex cursor kimi zcode; do
		case "$base" in
			*"$h"*) echo "$h"; return 0 ;;
		esac
	done
	return 1
}

skills_dir() {
	printf '%s/skills\n' "$1"
}

strip_comment() {
	local line="${1%%#*}"
	line="${line#"${line%%[![:space:]]*}"}"
	line="${line%"${line##*[![:space:]]}"}"
	printf '%s' "$line"
}

version_gt() {
	[ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]
}

best_tag() {
	local dir="$1" op="$2" ref="${3#v}" t v best="" best_v=""
	while IFS= read -r t; do
		v="${t#v}"
		case "$op" in
			">") version_gt "$v" "$ref" || continue ;;
			">=") [ "$v" = "$ref" ] || version_gt "$v" "$ref" || continue ;;
		esac
		if [ -z "$best" ] || version_gt "$v" "$best_v"; then
			best="$t"
			best_v="$v"
		fi
	done < <(git -C "$dir" tag -l | grep -E '^v?[0-9]')
	[ -n "$best" ] && printf '%s\n' "$best"
}

describe() {
	git -C "$1" describe --tags --exact-match "${2:-HEAD}" 2>/dev/null || git -C "$1" rev-parse --short "${2:-HEAD}"
}

resolve_ref() {
	local dir="$1" op="$2" ref="$3" r
	case "$op" in
		"") git -C "$dir" rev-parse -q --verify "HEAD^{commit}" ;;
		"=")
			for r in "refs/tags/$ref" "refs/tags/v${ref#v}" "refs/remotes/origin/$ref" "refs/heads/$ref" "$ref"; do
				git -C "$dir" rev-parse -q --verify "$r^{commit}" 2>/dev/null && return 0
			done
			return 1
			;;
		*)
			r="$(best_tag "$dir" "$op" "$ref")" || return 1
			git -C "$dir" rev-parse -q --verify "refs/tags/$r^{commit}"
			;;
	esac
}

sha() {
	if command -v sha256sum >/dev/null; then
		sha256sum
	else
		shasum -a 256
	fi
}

hash_tree() {
	(
		cd "$1" || exit 1
		find . \( -type f -o -type l \) ! -path "./$MARKER" | LC_ALL=C sort | while IFS= read -r f; do
			if [ -L "$f" ]; then
				printf '%s -> %s\n' "$f" "$(readlink "$f")"
			else
				printf '%s %s\n' "$f" "$(sha <"$f" | cut -d' ' -f1)"
			fi
		done | sha | cut -d' ' -f1
	)
}

marker_get() {
	sed -n "s/^$2=//p" "$1/$MARKER" | head -n 1
}

cache_path() {
	printf '%s/%s.git\n' "$CACHE_DIR" "$(printf '%s' "${1%.git}" | sed -E 's|^[A-Za-z][A-Za-z0-9+.-]*://||; s|[^A-Za-z0-9._-]|_|g')"
}

update_cache() {
	local url="$1" dir="$2"
	if [ -d "$dir" ]; then
		git -C "$dir" fetch -q --prune --force origin 2>&1
	else
		mkdir -p "$CACHE_DIR" || return 1
		if ! git clone -q --mirror "$url" "$dir" 2>&1; then
			rm -rf "$dir"
			return 1
		fi
	fi
}

sync_subskill() {
	local harness="$1" dir="$2" url="$3" path="$4" op="$5" ref="$6" cache="$7"
	local tag before="" target tmp
	tag="[$harness] ${dir##*/}"

	if [ -z "$cache" ]; then
		fail "$tag: $url is not available"
		return
	fi
	if [ -e "$dir" ]; then
		if [ ! -f "$dir/$MARKER" ]; then
			warn "$tag: $dir exists and was not installed from a subfolder, skipped"
			return
		fi
		if [ "$(marker_get "$dir" url)" != "$url" ] || [ "$(marker_get "$dir" path)" != "$path" ]; then
			warn "$tag: installed from $(marker_get "$dir" url) /$(marker_get "$dir" path), expected $url /$path, skipped"
			return
		fi
		if [ "$(hash_tree "$dir")" != "$(marker_get "$dir" hash)" ]; then
			warn "$tag: local changes present, skipped"
			return
		fi
		before="$(marker_get "$dir" commit)"
	fi

	if ! target="$(resolve_ref "$cache" "$op" "$ref")"; then
		if [ "$op" = "=" ]; then
			fail "$tag: ref '$ref' not found"
		elif [ -n "$before" ]; then
			warn "$tag: no tag $op $ref, left at $(describe "$cache" "$before")"
		else
			warn "$tag: no tag $op $ref, not installed"
		fi
		return
	fi
	if [ "$target" = "$before" ]; then
		log "$tag: up to date at $(describe "$cache" "$target")"
		return
	fi
	if [ "$(git -C "$cache" cat-file -t "$target:$path" 2>/dev/null)" != "tree" ]; then
		fail "$tag: folder /$path not found at $(describe "$cache" "$target")"
		return
	fi

	tmp="$(mktemp -d "${dir%/*}/.${dir##*/}.XXXXXX")" || { fail "$tag: cannot create a temporary folder"; return; }
	chmod 755 "$tmp"
	if ! git -C "$cache" archive --format=tar "$target:$path" | tar -x -C "$tmp"; then
		rm -rf "$tmp"
		fail "$tag: extraction of /$path failed"
		return
	fi
	printf 'url=%s\npath=%s\ncommit=%s\nhash=%s\n' "$url" "$path" "$target" "$(hash_tree "$tmp")" >"$tmp/$MARKER"
	if ! rm -rf "$dir" || ! mv "$tmp" "$dir"; then
		rm -rf "$tmp"
		fail "$tag: cannot replace $dir"
		return
	fi
	if [ -z "$before" ]; then
		log "$tag: installed /$path from $url at $(describe "$cache" "$target")"
	else
		log "$tag: updated $(describe "$cache" "$before") -> $(describe "$cache" "$target")"
	fi
}

sync_skill() {
	local harness="$1" dir="$2" url="$3" op="$4" ref="$5"
	local tag
	tag="[$harness] ${dir##*/}"
	local before after target branch origin

	if [ ! -e "$dir" ]; then
		if ! git clone -q "$url" "$dir" 2>&1; then
			fail "$tag: clone of $url failed"
			return
		fi
		log "$tag: cloned $url"
		before=""
	else
		if [ ! -d "$dir/.git" ]; then
			warn "$tag: $dir exists but is not a git checkout, skipped"
			return
		fi
		origin="$(git -C "$dir" remote get-url origin 2>/dev/null || true)"
		if [ "${origin%.git}" != "${url%.git}" ]; then
			warn "$tag: origin is '$origin', expected '$url', skipped"
			return
		fi
		if [ -n "$(git -C "$dir" status --porcelain 2>/dev/null)" ]; then
			warn "$tag: local changes present, skipped"
			return
		fi
		if ! git -C "$dir" fetch -q --prune --tags --force origin 2>&1; then
			fail "$tag: fetch failed"
			return
		fi
		before="$(git -C "$dir" rev-parse HEAD)"
	fi

	case "$op" in
		"")
			git -C "$dir" remote set-head origin -a >/dev/null 2>&1 || true
			branch="$(git -C "$dir" symbolic-ref -q --short refs/remotes/origin/HEAD)"
			branch="${branch#origin/}"
			if [ -z "$branch" ]; then
				fail "$tag: cannot find the default branch"
				return
			fi
			if ! git -C "$dir" checkout -q "$branch" 2>&1 || ! git -C "$dir" merge -q --ff-only "origin/$branch" 2>&1; then
				fail "$tag: cannot fast-forward $branch to origin/$branch"
				return
			fi
			;;
		*)
			if ! target="$(resolve_ref "$dir" "$op" "$ref")"; then
				if [ "$op" = "=" ]; then
					fail "$tag: ref '$ref' not found"
				else
					warn "$tag: no tag $op $ref, left at $(describe "$dir")"
				fi
				return
			fi
			if [ "$target" != "$(git -C "$dir" rev-parse HEAD)" ] && ! git -C "$dir" checkout -q --detach "$target" 2>&1; then
				fail "$tag: checkout of $ref failed"
				return
			fi
			;;
	esac

	after="$(git -C "$dir" rev-parse HEAD)"
	if [ -z "$before" ]; then
		log "$tag: at $(describe "$dir")"
	elif [ "$before" != "$after" ]; then
		log "$tag: updated ${before:0:10} -> $(describe "$dir")"
	else
		log "$tag: up to date at $(describe "$dir")"
	fi
}

main() {
	case "${1:-}" in
		-h | --help) usage; exit 0 ;;
		-V | --version) echo "skills-autoupdate $VERSION"; exit 0 ;;
		"") ;;
		*) usage >&2; exit 2 ;;
	esac

	command -v git >/dev/null || { log "ERROR git not found"; exit 1; }
	[ -r "$SKILLS_FILE" ] || { log "ERROR $SKILLS_FILE not found"; exit 1; }
	[ -r "$HARNESSES_FILE" ] || { log "ERROR $HARNESSES_FILE not found"; exit 1; }

	if command -v flock >/dev/null; then
		mkdir -p "$(dirname "$LOCK_FILE")"
		exec 9>"$LOCK_FILE"
		flock -n 9 || { log "another run is in progress, exiting"; exit 0; }
	fi

	local -a h_names=() h_roots=() s_urls=() s_paths=() s_ops=() s_refs=() s_names=() paths=() names=() parts=()
	local raw line name root real seen="" seen_names="" fetched="" url op ref p i j k cache

	while IFS= read -r raw || [ -n "$raw" ]; do
		line="$(strip_comment "$raw")"
		[ -z "$line" ] && continue
		if name="$(normalize_name "$(printf '%s' "$line" | tr '[:upper:]' '[:lower:]')")"; then
			root="$(default_root "$name")"
		else
			root="$(expand_path "$line")"
			if [ ! -d "$root" ]; then
				warn "harness path $root not found, skipped"
				continue
			fi
			if ! name="$(detect_harness "$root")"; then
				warn "cannot recognize the harness in $root, skipped"
				continue
			fi
		fi
		if [ ! -d "$root" ]; then
			log "[$name] $root not found, harness not installed, skipped"
			continue
		fi
		real="$(cd "$root" && pwd -P)"
		case "$seen" in
			*"|$real|"*) continue ;;
		esac
		seen="$seen|$real|"
		h_names+=("$name")
		h_roots+=("$root")
	done <"$HARNESSES_FILE"

	while IFS= read -r raw || [ -n "$raw" ]; do
		line="$(strip_comment "$raw")"
		[ -z "$line" ] && continue
		if [[ ! "$line" =~ $LINE_RE ]]; then
			warn "invalid skill line '$line', skipped"
			continue
		fi
		if [ -n "${BASH_REMATCH[4]}" ] && [ -z "${BASH_REMATCH[5]}" ]; then
			warn "missing version in '$line', skipped"
			continue
		fi
		url="${BASH_REMATCH[1]%/}"
		op="${BASH_REMATCH[4]}"
		ref="${BASH_REMATCH[5]}"
		if [ -z "${BASH_REMATCH[2]}" ]; then
			name="${url##*/}"
			name="${name##*:}"
			paths=("")
			names=("${name%.git}")
		else
			paths=()
			names=()
			IFS=, read -r -a parts <<<"${BASH_REMATCH[3]}"
			for p in "${parts[@]}"; do
				p="$(printf '%s' "$p" | sed -E 's|/+|/|g; s|^/||; s|/$||')"
				if [ -z "$p" ] || [[ "/$p/" == */../* || "/$p/" == */./* ]]; then
					warn "invalid subfolder in '$line', skipped"
					continue
				fi
				paths+=("$p")
				names+=("${p##*/}")
			done
		fi
		for k in "${!paths[@]}"; do
			case "$seen_names" in
				*"|${names[$k]}|"*)
					warn "skill name '${names[$k]}' is listed more than once, '$line' skipped"
					continue
					;;
			esac
			seen_names="$seen_names|${names[$k]}|"
			s_urls+=("$url")
			s_paths+=("${paths[$k]}")
			s_ops+=("$op")
			s_refs+=("$ref")
			s_names+=("${names[$k]}")
		done
	done <"$SKILLS_FILE"

	[ "${#h_names[@]}" -eq 0 ] && { log "no harness found, nothing to do"; exit 0; }
	[ "${#s_urls[@]}" -eq 0 ] && { log "no skill listed, nothing to do"; exit 0; }

	local -a s_caches=()
	for j in "${!s_urls[@]}"; do
		s_caches[j]=""
		[ -z "${s_paths[$j]}" ] && continue
		cache="$(cache_path "${s_urls[$j]}")"
		case "$fetched" in
			*"|$cache|"*) ;;
			*"|!$cache|"*) continue ;;
			*)
				if ! update_cache "${s_urls[$j]}" "$cache"; then
					fail "cannot fetch ${s_urls[$j]}"
					fetched="$fetched|!$cache|"
					continue
				fi
				fetched="$fetched|$cache|"
				;;
		esac
		s_caches[j]="$cache"
	done

	for i in "${!h_names[@]}"; do
		root="$(skills_dir "${h_roots[$i]}")"
		if ! mkdir -p "$root"; then
			fail "[${h_names[$i]}] cannot create $root"
			continue
		fi
		for j in "${!s_urls[@]}"; do
			if [ -z "${s_paths[$j]}" ]; then
				sync_skill "${h_names[$i]}" "$root/${s_names[$j]}" "${s_urls[$j]}" "${s_ops[$j]}" "${s_refs[$j]}"
			else
				sync_subskill "${h_names[$i]}" "$root/${s_names[$j]}" "${s_urls[$j]}" "${s_paths[$j]}" "${s_ops[$j]}" "${s_refs[$j]}" "${s_caches[$j]}"
			fi
		done
	done

	[ "$failures" -eq 0 ] || { log "finished with $failures error(s)"; exit 1; }
	log "finished"
}

main "$@"
