#!/usr/bin/env bash
# post-pull.sh — homelab-context sync hook.
# Replaces raw `git pull` in the launchd/systemd timer.
# Runs after every git pull to auto-setup tools from the repo.
#
# Convention: any script at tools/setup-*.sh is sourced/exec'd after pull.
# This lets us ship new tooling to all agent hosts via a simple git push.

set -euo pipefail

CONTEXT_DIR="${HOMELAB_CONTEXT_DIR:-/opt/homelab-context}"

# Git safe.directory workaround: the repo is owned by the regular user
# but launchd runs as root. Run git as the repo owner.
if command -v realpath &>/dev/null; then
  REPO_REAL=$(realpath "$CONTEXT_DIR")
elif command -v grealpath &>/dev/null; then
  REPO_REAL=$(grealpath "$CONTEXT_DIR")
else
  REPO_REAL=$(perl -e 'print Cwd::abs_path(shift)' "$CONTEXT_DIR" 2>/dev/null || echo "/Users/dtoro/oikos")
fi
REPO_OWNER=$(stat -f "%Su" "$REPO_REAL" 2>/dev/null || echo "dtoro")

# 1. Git pull (as repo owner to avoid safe.directory issues)
if [ "$REPO_OWNER" != "root" ] && command -v sudo &>/dev/null; then
  sudo -u "$REPO_OWNER" git -C "$CONTEXT_DIR" pull --ff-only --quiet 2>&1 | grep -v "failed to store" || \
    echo "[post-pull] git pull failed (network?) continuing..."
else
  git -C "$CONTEXT_DIR" pull --ff-only --quiet 2>&1 || \
    echo "[post-pull] git pull failed (network?) continuing..."
fi

# 2. Run any auto-setup scripts
for setup_script in "$CONTEXT_DIR"/tools/setup-*.sh; do
  [ -f "$setup_script" ] || continue
  echo "[post-pull] running $setup_script..."
  bash "$setup_script" || echo "[post-pull] WARNING: $setup_script exited with code $?"
done

# 3. Symlink AGENTS.md for agent orientation (macOS)
if [ "$(uname)" = "Darwin" ]; then
  ln -sf "$CONTEXT_DIR/AGENTS.md" /etc/AGENTS.md 2>/dev/null || true
fi