#!/bin/bash
# Claude setup for Rodney: Claude Code + an Obsidian "brain" vault + terminal shortcuts.
# Safe to re-run. Never overwrites a file that already exists. Needs no Homebrew.
#
# Usage: ./setup.sh [--dry-run] [--no-install] [--vault FOLDER]
#   --dry-run     show what would happen, change nothing
#   --no-install  skip the Claude Code download (everything else still runs)
#   --vault DIR   where the Obsidian vault goes (default ~/Documents/ClaudeBrain)
set -euo pipefail

DRY=0
NOINSTALL=0
VAULT_DIR="${VAULT_DIR:-$HOME/Documents/ClaudeBrain}"

while [ $# -gt 0 ]; do
  case "$1" in
    --dry-run) DRY=1 ;;
    --no-install) NOINSTALL=1 ;;
    --vault) shift; VAULT_DIR="${1:?--vault needs a folder}" ;;
    -h|--help) sed -n '2,9p' "$0"; exit 0 ;;
    *) echo "Unknown option: $1" >&2; exit 2 ;;
  esac
  shift
done

say()  { printf '%s\n' "$*"; }
step() { printf '\n== %s ==\n' "$*"; }

# put <path>: file content arrives on stdin. Never overwrites an existing file.
put() {
  local p="$1"
  if [ -e "$p" ]; then say "  keep    $p (already there)"; cat >/dev/null; return 0; fi
  if [ "$DRY" = 1 ]; then say "  would   create $p"; cat >/dev/null; return 0; fi
  mkdir -p "$(dirname "$p")"
  cat > "$p"
  say "  created $p"
}

mkd() {
  if [ -d "$1" ]; then return 0; fi
  if [ "$DRY" = 1 ]; then say "  would   make folder $1"; return 0; fi
  mkdir -p "$1"
}

[ "$DRY" = 1 ] && say "DRY RUN: nothing will be changed."

# ---------------------------------------------------------------- 0. checks
step "0. Checking your Mac"
[ "$(uname -s)" = "Darwin" ] || say "  note: this guide is written for macOS (iTerm2 and Wispr Flow's fn key are Mac)."
command -v curl >/dev/null 2>&1 || { say "  curl is missing, cannot continue."; exit 1; }
say "  ok: macOS tools found. Homebrew is NOT needed."

# ---------------------------------------------------------------- 1. Claude Code
step "1. Claude Code"
if command -v claude >/dev/null 2>&1 || [ -x "$HOME/.local/bin/claude" ]; then
  say "  ok: already installed"
elif [ "$NOINSTALL" = 1 ]; then
  say "  skipped (--no-install). To install later run: curl -fsSL https://claude.ai/install.sh | bash"
elif [ "$DRY" = 1 ]; then
  say "  would   run: curl -fsSL https://claude.ai/install.sh | bash"
else
  say "  installing with Anthropic's official installer (no progress bar, give it a minute)..."
  curl -fsSL https://claude.ai/install.sh | bash
fi

# ---------------------------------------------------------------- 2. Obsidian vault
step "2. Your Obsidian vault: $VAULT_DIR"
for d in Inbox Projects People Resources Archive raw wiki outputs; do mkd "$VAULT_DIR/$d"; done

put "$VAULT_DIR/.obsidian/daily-notes.json" <<'EOF'
{
  "folder": "raw",
  "format": "YYYY-MM-DD",
  "autorun": false
}
EOF

put "$VAULT_DIR/Brain.md" <<'EOF'
---
tags: [index]
---

# Brain

The front page of this vault. Claude reads this first.

## Start here
- [[Vault Conventions]]: where notes go and what to call them.
- [[Token Saving Rules]]: how to keep Claude fast and usage low.
- [[Claude Tips]]: shortcuts and habits worth learning first.

## Folders
- `Inbox/`: dump anything here, sort it later (or ask Claude to sort it).
- `raw/`: daily notes, one per day, named `YYYY-MM-DD`.
- `Projects/`: one note per project.
- `wiki/`: rules and reference you want to keep.
- `outputs/`: finished work.
- `Archive/`: finished or shelved notes.
EOF

put "$VAULT_DIR/wiki/Vault Conventions.md" <<'EOF'
---
tags: [wiki, rules]
---

# Vault Conventions

| What | Folder |
|---|---|
| Unsorted capture | `Inbox/` |
| Daily notes (`YYYY-MM-DD`) | `raw/` |
| One note per project | `Projects/` |
| People | `People/` |
| Reference material | `Resources/` |
| Rules and how-tos | `wiki/` |
| Finished work | `outputs/` |
| Finished or shelved | `Archive/` |

## Rules
- Link notes by name with double brackets, like [[Brain]].
- Project status words: `Idea`, `Active`, `Live`, `Blocked`, `Done`. Use exactly these.
- Tags are lowercase and singular.
- Never delete a note to tidy up. Move it to `Archive/`.

Related: [[Brain]]
EOF

put "$VAULT_DIR/wiki/Token Saving Rules.md" <<'EOF'
---
tags: [wiki, rules]
---

# Token Saving Rules

## For Claude
1. Ask at most 1 clarifying question, then do the work.
2. Edit the lines that need changing. Do not rewrite whole files.
3. Do not re-read a file already read in this session.
4. Keep replies short.

## For me
1. One topic per session. New topic, new session (`/clear`).
2. Name the project in the first line of a request.
3. Batch asks: three changes in one message beats three messages.
4. Use a lighter model for quick jobs (captions, small edits). Save the strongest model for big builds.

Related: [[Brain]]
EOF

put "$VAULT_DIR/wiki/Claude Tips.md" <<'EOF'
---
tags: [wiki, tips]
---

# Claude Tips

## In iTerm2
- New line without sending: `Shift+Enter` (works in iTerm2 as is). `Ctrl+J` works in any terminal.
- Jump back and forth between turns: `Cmd+Shift+Up` in iTerm2.
- Cycle permission modes: `Shift+Tab`. Stop what Claude is doing: `Esc`.
- Open the prompt in your editor: `Ctrl+G`. Stash a half-written prompt: `Ctrl+S`.
- Model picker `Option+P`, thinking toggle `Option+T` (needs Option as Meta, see the setup guide).
- Get a desktop ping when Claude finishes or needs you: iTerm2 > Settings > Profiles > Terminal > tick "Notification Center Alerts" > Filter Alerts > "Send escape sequence-generated alerts".

## With Wispr Flow (voice)
- Hold `fn`, talk, let go: your words land in the prompt. Read it before you press Enter.
- Hands-free: `fn + Space` to start, again to stop (20 minute limit).
- Best for long prompts and brain dumps. Do not dictate passwords or keys.

## Habits that pay off
- Type `brain` in a new terminal tab to open Claude inside this vault.
- Dump everything into `Inbox/`, then tell Claude: "sort my Inbox using Vault Conventions".
- Run `/init` once in a code project so Claude writes that project's `CLAUDE.md`.
- When Claude gets something wrong, say so once, then ask it to add one line to `~/.claude/LESSONS.md`.
- "Done" means checked: ask Claude to run the build or tests and show the output before it says finished.

Related: [[Brain]]
EOF

put "$VAULT_DIR/CLAUDE.md" <<'EOF'
# This folder is my Obsidian vault

- Read `Brain.md` first. It is the index.
- Notes are markdown. Link by note name with `[[double brackets]]`.
- Where things go is in `wiki/Vault Conventions.md`. Follow it.
- New unsorted captures go to `Inbox/`. Daily notes go to `raw/` as `YYYY-MM-DD.md`.
- Never delete or overwrite a note unless I ask. Edit the lines that need changing.
- Keep replies short. Ask at most one clarifying question.
EOF

# ---------------------------------------------------------------- 3. Claude's own memory
step "3. Claude's global instructions"
CLAUDE_DIR="$HOME/.claude"
GLOBAL="$CLAUDE_DIR/CLAUDE.md"
MARK="<!-- created by rodney-claude-setup -->"
if [ -e "$GLOBAL" ] && grep -qF "$MARK" "$GLOBAL"; then
  say "  keep    $GLOBAL (this setup made it earlier)"
else
  if [ -e "$GLOBAL" ]; then
    say "  You already have your own $GLOBAL. Not touching it."
    say "  A starter you can copy from goes to $CLAUDE_DIR/CLAUDE.starter.md"
    GLOBAL="$CLAUDE_DIR/CLAUDE.starter.md"
  fi
  {
    printf '%s\n\n' "$MARK"
    sed "s|__VAULT__|$VAULT_DIR|g" <<'EOF'
## How I like to work
- Keep answers short. Ask at most one clarifying question, then do the work.
- Edit, do not rewrite. Do not re-read files already read this session.
- Not done until checked: run the build or tests and show the result.
- Read `~/.claude/LESSONS.md` before starting. When I correct you, add one line there.

## My notes
- My Obsidian vault is `__VAULT__`. Its `Brain.md` is the index.
EOF
  } | put "$GLOBAL"
fi

put "$CLAUDE_DIR/LESSONS.md" <<'EOF'
# Lessons (compounding rules)

One line each, newest at the bottom. Format: `- YYYY-MM-DD [area] the rule`
EOF

# ---------------------------------------------------------------- 4. shell shortcuts
step "4. Terminal shortcuts (~/.zshrc)"
ZSHRC="$HOME/.zshrc"
BEGIN="# >>> claude-setup (managed block) >>>"
END="# <<< claude-setup <<<"
if [ -f "$ZSHRC" ] && grep -qF "$BEGIN" "$ZSHRC"; then
  say "  keep    shortcuts already in $ZSHRC"
elif [ "$DRY" = 1 ]; then
  say "  would   add shortcuts 'brain' and 'cc' to $ZSHRC (backup first)"
else
  if [ -f "$ZSHRC" ] && [ ! -e "$ZSHRC.bak-claude-setup" ]; then
    cp "$ZSHRC" "$ZSHRC.bak-claude-setup"
    say "  backup  $ZSHRC.bak-claude-setup"
  fi
  {
    printf '\n%s\n' "$BEGIN"
    sed "s|__VAULT__|$VAULT_DIR|g" <<'EOF'
case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH" ;; esac
alias brain='cd "__VAULT__" && claude'
alias cc='claude'
EOF
    printf '%s\n' "$END"
  } >> "$ZSHRC"
  say "  added   'brain' (open Claude inside your vault) and 'cc' (short for claude)"
fi

# ---------------------------------------------------------------- 5. what is left
step "5. Do these by hand (they need a click or a login)"
cat <<EOF
  [ ] iTerm2    https://iterm2.com/downloads.html  -> drag to Applications
  [ ] Obsidian  https://obsidian.md/download       -> Open folder as vault -> $VAULT_DIR
  [ ] Wispr     https://wisprflow.ai               -> drag to Applications, allow Microphone + Accessibility
  [ ] Claude    open a NEW iTerm tab, type: brain   -> sign in when asked (your own account)
  Full walkthrough: GUIDE.md
EOF
say ""
say "Done."
