#!/bin/sh
# Cooper Email project installer. https://cooperemail.com/install.sh
# Operator: Avatar 8 LLC <ops@avatar33.com>
# Appends an Email section to existing agent instruction files. No API key is written.
set -eu

MCP=0
YES=0
DIR=.

usage() {
  echo "Usage: sh install.sh [--mcp] [--yes] [--dir DIR]"
  echo "Append an Email section to AGENTS.md, CLAUDE.md, GEMINI.md, and .cursor/rules when they exist."
  echo "--mcp registers Claude Code and Codex after printing the change. --yes applies it."
}

while [ $# -gt 0 ]; do
  case "$1" in
    --mcp) MCP=1 ;;
    --yes) YES=1 ;;
    --dir)
      shift
      if [ $# -eq 0 ]; then
        echo "--dir needs a path" >&2
        exit 1
      fi
      DIR=$1
      ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown argument $1" >&2; exit 1 ;;
  esac
  shift
done

if [ ! -d "$DIR" ]; then
  echo "Not a directory: $DIR" >&2
  exit 1
fi

SECTION_FILE=$(mktemp)
RULES_FILE=$(mktemp)
trap 'rm -f "$SECTION_FILE" "$RULES_FILE"' EXIT HUP INT TERM

cat > "$SECTION_FILE" << 'COOPER_SECTION'
<!-- cooper-email:start -->
## Email

When this project's agent needs to send or receive email, get a verification code, or give itself an address, use Cooper Email (MCP https://cooperemail.com/mcp, docs https://cooperemail.com/llms.txt). Ask the human before emailing a new recipient. Keep the API key in a file. Never print it.
<!-- cooper-email:end -->
COOPER_SECTION

cat > "$RULES_FILE" << 'COOPER_RULES'
---
description: Use Cooper Email when this project needs to send or receive email, get a verification code, or give itself an address.
alwaysApply: true
---

<!-- cooper-email:start -->
## Email

When this project's agent needs to send or receive email, get a verification code, or give itself an address, use Cooper Email (MCP https://cooperemail.com/mcp, docs https://cooperemail.com/llms.txt). Ask the human before emailing a new recipient. Keep the API key in a file. Never print it.
<!-- cooper-email:end -->
COOPER_RULES

CHANGED=0

apply_file() {
  target=$1
  [ -f "$target" ] || return 0
  tmp=$(mktemp)
  if grep -qF '<!-- cooper-email:start -->' "$target"; then
    if ! grep -qF '<!-- cooper-email:end -->' "$target"; then
      rm -f "$tmp"
      echo "Skipped $target: it has the start marker but no end marker. Fix it by hand, then re-run."
      return 0
    fi
    awk '
      NR == FNR { section = section $0 ORS; next }
      index($0, "<!-- cooper-email:start -->") { if (!done) { printf "%s", section; done = 1 }; skip = 1; next }
      index($0, "<!-- cooper-email:end -->") { skip = 0; next }
      skip != 1 { print }
    ' "$SECTION_FILE" "$target" > "$tmp"
  else
    if [ -s "$target" ]; then
      cat "$target" > "$tmp"
      # One blank line before the section, whether or not the file ends in a newline.
      if [ -n "$(tail -c 1 "$target")" ]; then printf '\n' >> "$tmp"; fi
      printf '\n' >> "$tmp"
    fi
    cat "$SECTION_FILE" >> "$tmp"
  fi
  if cmp -s "$tmp" "$target"; then
    rm -f "$tmp"
    echo "Unchanged $target"
    return 0
  fi
  # Write in place so the file keeps its mode, owner, and symlinks.
  cat "$tmp" > "$target"
  rm -f "$tmp"
  CHANGED=1
  echo "Updated $target"
}

found=0
for name in AGENTS.md CLAUDE.md GEMINI.md; do
  if [ -f "$DIR/$name" ]; then
    found=1
    apply_file "$DIR/$name"
  fi
done

if [ -f "$DIR/.cursor/rules" ]; then
  found=1
  apply_file "$DIR/.cursor/rules"
elif [ -d "$DIR/.cursor/rules" ]; then
  found=1
  rule="$DIR/.cursor/rules/cooper-email.mdc"
  if [ -f "$rule" ]; then
    apply_file "$rule"
  else
    cp "$RULES_FILE" "$rule"
    echo "Created $rule"
    CHANGED=1
  fi
fi

if [ "$found" -eq 0 ]; then
  echo "No agent instruction files found (AGENTS.md, CLAUDE.md, GEMINI.md, .cursor/rules)."
fi

if [ "$CHANGED" -eq 1 ]; then
  echo "Section written (no API key):"
  cat "$SECTION_FILE"
fi

if [ "$MCP" -ne 1 ]; then
  exit 0
fi

echo "MCP changes (no API key is written):"
echo "Claude Code: claude mcp add --transport http cooper-email https://cooperemail.com/mcp"
echo "  Registers cooper-email with Claude Code. Default scope is local."
echo "Codex: codex mcp add cooper-email --url https://cooperemail.com/mcp"
echo "  If codex is not on PATH, append this manual fallback to ${HOME}/.codex/config.toml:"
echo '[mcp_servers.cooper-email]'
echo 'url = "https://cooperemail.com/mcp"'

if [ "$YES" -ne 1 ]; then
  if [ -t 0 ]; then
    printf "Apply these MCP changes? [y/N] "
    read -r ans || ans=
    case "$ans" in
      y|Y|yes|YES) ;;
      *) echo "MCP not changed."; exit 0 ;;
    esac
  else
    echo "MCP not changed. Re-run with --mcp --yes to apply."
    exit 0
  fi
fi

if command -v claude >/dev/null 2>&1; then
  if claude mcp get cooper-email >/dev/null 2>&1; then
    echo "Claude Code already has cooper-email. Left unchanged."
  else
    echo "Running: claude mcp add --transport http cooper-email https://cooperemail.com/mcp"
    claude mcp add --transport http cooper-email https://cooperemail.com/mcp
  fi
else
  echo "claude is not on PATH. Claude Code MCP was not changed."
fi

CODEX_CONFIG="${HOME}/.codex/config.toml"
if [ -f "$CODEX_CONFIG" ] && grep -q '\[mcp_servers\.cooper-email\]' "$CODEX_CONFIG"; then
  echo "Codex config already has [mcp_servers.cooper-email] in $CODEX_CONFIG. Left unchanged."
  exit 0
fi

if command -v codex >/dev/null 2>&1; then
  echo "Running: codex mcp add cooper-email --url https://cooperemail.com/mcp"
  codex mcp add cooper-email --url https://cooperemail.com/mcp
  exit 0
fi

echo "codex is not on PATH. Appending the manual fallback to $CODEX_CONFIG"
mkdir -p "${HOME}/.codex"
if [ -f "$CODEX_CONFIG" ]; then
  printf '\n\n[mcp_servers.cooper-email]\nurl = "https://cooperemail.com/mcp"\n' >> "$CODEX_CONFIG"
else
  printf '[mcp_servers.cooper-email]\nurl = "https://cooperemail.com/mcp"\n' > "$CODEX_CONFIG"
  chmod 600 "$CODEX_CONFIG"
fi
