#!/bin/bash
# Automatically learn email addresses from sent/received mail

ABOOK_FILE="$HOME/.abook/addressbook"
mkdir -p "$HOME/.abook"
touch "$ABOOK_FILE"

# Extract all email addresses from notmuch database
notmuch address --output=sender --output=recipients '*' |
  sort -u |
  while read -r email; do
    # Check if email is already in abook
    if ! grep -q "$email" "$ABOOK_FILE" 2>/dev/null; then
      # Extract name and email
      if [[ $email =~ ^(.+)\<(.+)\>$ ]]; then
        NAME="${BASH_REMATCH[1]}"
        EMAIL="${BASH_REMATCH[2]}"
      else
        NAME=""
        EMAIL="$email"
      fi

      # Add to abook (skip if already exists)
      echo "[format]
program=abook
version=0.6.1

[0]
name=$NAME
email=$EMAIL
" >>"$ABOOK_FILE"
    fi
  done

echo "Address book updated: $(grep -c '^\[' "$ABOOK_FILE") entries"
