#!/usr/bin/env bash
# upstream-key-set [name] — store a caller's model credential for the gate
# without echoing it. One line per name in ~/.config/shorashim/upstream_keys
# (0600): "<name> <value>". The line for <name> is replaced; the others
# stay. Names: anthropic (default), infomaniak (the AI Services API
# token), infomaniak_product (the AI Services product id — digits; GET
# https://api.infomaniak.com/1/ai lists it). Run from a real terminal.
set -e
NAME="${1:-anthropic}"
case "$NAME" in *[!a-z_]*|"") echo "name must be lowercase letters and _" >&2; exit 1;; esac
F="$HOME/.config/shorashim/upstream_keys"
read -rsp "$NAME (not echoed): " VAL; echo
[ -n "$VAL" ] || { echo "empty — nothing written"; exit 1; }
case "$VAL" in *[[:space:]]*) echo "no whitespace in a key" >&2; exit 1;; esac
mkdir -p "$(dirname "$F")"
umask 077
TMP="$(mktemp "$(dirname "$F")/.upstream_keys.XXXXXX")"
{ [ -f "$F" ] && awk -v n="$NAME" '$1!=n' "$F"; printf '%s %s\n' "$NAME" "$VAL"; } > "$TMP"
mv "$TMP" "$F"; chmod 600 "$F"
echo "written $NAME to $F (0600); names now: $(awk '{print $1}' "$F" | tr '\n' ' ')"
