#!/bin/zsh
# save-key: moves an API key from your Mac's clipboard into the Mac's Keychain, then clears the clipboard.
# It never prints the key, so it stays out of the chat, your shell history and every plain-text file.
#
#   Copy the key on the Mac (or on an iPhone next to it, with Handoff on), then run:
#     ~/studio/bin/save-key XAI_API_KEY
#
# It also adds one line to ~/.zshrc that loads the key from the Keychain when a new shell starts.
# That line holds no secret. Restart Claude Code (and any `claude remote-control` window) afterwards.
# From https://massonit.com/ai-studio-from-your-phone/

name="$1"
if [[ ! "$name" =~ ^[A-Z][A-Z0-9_]*$ ]]; then
  print "Usage: save-key NAME, in capitals, like XAI_API_KEY or GEMINI_API_KEY."
  exit 1
fi

key="$(pbpaste)"
key="${key//[[:space:]]/}"
if (( ${#key} < 20 )); then
  print "The clipboard doesn't look like an API key (${#key} characters). Copy the key on this Mac and try again."
  exit 1
fi

service="studio-$name"
security add-generic-password -U -a "$USER" -s "$service" -l "$name (save-key)" -w "$key" >/dev/null || {
  print "Couldn't save to the Keychain. Nothing was changed."
  exit 1
}
key=""
pbcopy </dev/null

line="export $name=\"\$(security find-generic-password -a \"\$USER\" -s $service -w 2>/dev/null)\""
touch "$HOME/.zshrc"
grep -qxF "$line" "$HOME/.zshrc" || print -r -- "$line" >>"$HOME/.zshrc"

print "Saved $name to your Keychain and cleared the clipboard."
print "If you use a clipboard manager (Raycast, Paste, Alfred), delete the key from its history too."
print "Now quit and reopen Claude Code, and restart 'claude remote-control' if it's running."
