#!/bin/bash

set -uo pipefail

# Kullanım: ./keychain-save.sh <service-adı>
# Örnek:    ./keychain-save.sh github-pat
#           ./keychain-save.sh firebase-sa

SERVICE_NAME="${1:-}"

if [ -z "$SERVICE_NAME" ]; then
    echo "Kullanım: $0 <service-adı>"
    echo "Örnek:    $0 github-pat"
    exit 1
fi

echo "Ne tür bir secret kaydedeceksin?"
echo "  1) Personal Access Token / API Key"
echo "  2) JSON dosyası (service account vb.)"
read -rp "Seçim (1/2): " CHOICE

case "$CHOICE" in
    1)
        read -rsp "Token'ı yapıştır (gizli yazılır): " SECRET
        echo ""
        if [ -z "$SECRET" ]; then
            echo "Hata: Token boş olamaz."
            exit 1
        fi
        ;;
    2)
        read -rp "JSON dosya yolunu gir: " JSON_PATH
        # Kullanıcının girdiği tırnak işaretlerini temizle
        JSON_PATH="${JSON_PATH//\'/}"
        JSON_PATH="${JSON_PATH//\"/}"
        # Tilde (~) expand
        JSON_PATH="${JSON_PATH/#\~/$HOME}"
        if [ ! -f "$JSON_PATH" ]; then
            echo "Hata: Dosya bulunamadı: $JSON_PATH"
            exit 1
        fi
        # JSON'ı tek satıra sıkıştırıp base64'le
        SECRET=$(base64 < "$JSON_PATH")
        if [ -z "$SECRET" ]; then
            echo "Hata: Dosya okunamadı."
            exit 1
        fi
        echo "JSON base64 olarak encode edildi."
        ;;
    *)
        echo "Geçersiz seçim."
        exit 1
        ;;
esac

# Locate the resolver with an existence check, not a `.`-chain.
#
# Sourcing a file that does not exist aborts the shell under `set -e` - `||` included -
# so `. <candidate> || . <candidate> || { error }` reaches neither its later candidates
# nor its error branch. Every fetcher used that shape starting from `$HOME/.claude/...`,
# so on a Copilot-only or Codex-only install they all died with a bare exit 1 and no
# message. Reordering does not help: whichever candidate is absent aborts at that point.
# Checking for the file before sourcing it is the only safe form.
for _cred_resolver in \
  "$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)/credential-store-resolver.sh" \
  "$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")/../lib" 2>/dev/null && pwd)/credential-store-resolver.sh" \
  "$HOME/.claude/lib/credential-store-resolver.sh" \
  "$HOME/.copilot/lib/credential-store-resolver.sh" \
  "$HOME/.codex/lib/credential-store-resolver.sh"; do
  [ -f "$_cred_resolver" ] || continue
  # shellcheck source=/dev/null
  . "$_cred_resolver" 2>/dev/null || true
  # `if`, not `[ ... ] && break`: the latter is the loop body's last command and returns
  # 1 when CRED_STORE is still empty, which under `set -e` kills the loop on the first
  # candidate that does not resolve - the very case the loop exists to survive.
  if [ -n "${CRED_STORE:-}" ]; then break; fi
done
unset _cred_resolver
if [ -z "${CRED_STORE:-}" ]; then
  echo "Hata: credential-store bulunamadi. Kurulum: npx @mmerterden/multi-agent-pipeline install"
  exit 1
fi
CRED="$CRED_STORE"

"$CRED" delete "$SERVICE_NAME" >/dev/null 2>&1 || true
# Secret goes through stdin ("set <key> -") so it never appears on argv.
if printf '%s' "$SECRET" | "$CRED" set "$SERVICE_NAME" -; then
    echo "Kaydedildi: $SERVICE_NAME (platform: $("$CRED" platform))"
    echo ""
    echo "Okumak icin:"
    echo "  $CRED get \"$SERVICE_NAME\""
    if [ "$CHOICE" = "2" ]; then
        echo ""
        echo "JSON'a geri cevirmek icin:"
        echo "  $CRED get \"$SERVICE_NAME\" | base64 -d"
    fi
else
    echo "Hata: Kaydedilemedi."
    exit 1
fi
