#!/bin/bash
# GitHub SSH Key Oluşturma ve Kurulum Scripti
#
# HEADLESS: her soru bir env değişkeniyle önceden cevaplanabilir ve terminal
# yoksa script SORMAZ. Üç `read -p` koruma olmadan duruyordu; bir launchd
# ajanının ya da uzak bir kabuğun altında ilki sonsuza kadar bekler ve dışarı
# hiçbir şey yazmaz, yani kurulum "asılı kaldı" diye görünür. Bir sunucuda
# çalışması hedeflenen bir aracın sessizce beklemesi, açıkça reddetmesinden
# kötüdür.
#
#   MULTI_AGENT_UNATTENDED=1  terminal olsa bile soru sorulmaz
#   SSH_SETUP_EMAIL     anahtarın yorum alanına yazılacak e-posta (zorunlu)
#   SSH_SETUP_OVERWRITE e|h  - var olan anahtarın üzerine yazılsın mı (varsayılan h)
#   SSH_SETUP_TEST      e|h  - sonunda github.com'a bağlantı denensin mi (varsayılan h)

set -euo pipefail

# Every line a person reads resolves through the table below, so this script
# answers to the same language preference the rest of the pipeline answers to.
#
# The file is checked for before it is sourced, because a `.` of a path that is
# not there takes the shell with it and the later candidates are never reached.
for _ma_uf in \
  "$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)/user-facing.sh" \
  "$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")/../lib" 2>/dev/null && pwd)/user-facing.sh" \
  "$HOME/.claude/lib/user-facing.sh" \
  "$HOME/.copilot/lib/user-facing.sh" \
  "$HOME/.codex/lib/user-facing.sh"; do
  [ -f "$_ma_uf" ] || continue
  # shellcheck source=/dev/null
  . "$_ma_uf" 2>/dev/null || true
  if command -v ma_output_lang >/dev/null 2>&1; then break; fi
done
unset _ma_uf
if ! command -v ma_output_lang >/dev/null 2>&1; then
  echo "Error: user-facing.sh not found. Install: npx @mmerterden/multi-agent-pipeline install" >&2
  exit 1
fi
OUT_LANG=$(ma_output_lang)

# One table, both languages on the same line, so a wording change cannot land
# on one of them. English is the default and the fallback.
#
# The overwrite and test prompts keep asking for `e` or `h` in either language:
# the same two letters answer SSH_SETUP_OVERWRITE and SSH_SETUP_TEST, and the
# comparisons below read them.
msg() { # $1 = key, $2.. = printf arguments
    local key="$1" en tr fmt
    shift
    case "$key" in
        title)
            en='=== GitHub SSH Key Setup ==='
            tr='=== GitHub SSH Key Kurulumu ===' ;;
        ask-email)
            en='Enter your GitHub email address: '
            tr='GitHub e-posta adresinizi girin: ' ;;
        email-empty)
            en='Error: the email address cannot be empty.'
            tr='Hata: E-posta adresi boş olamaz.' ;;
        email-missing-unattended)
            en='Error: MULTI_AGENT_UNATTENDED=1 and SSH_SETUP_EMAIL is not set.'
            tr='Hata: MULTI_AGENT_UNATTENDED=1 ve SSH_SETUP_EMAIL tanımlı değil.' ;;
        email-missing-headless)
            en='Error: there is no terminal and SSH_SETUP_EMAIL is not set.'
            tr='Hata: terminal yok ve SSH_SETUP_EMAIL tanımlı değil.' ;;
        headless-hint)
            en='      To run it headless: SSH_SETUP_EMAIL=you@example.com %s'
            tr='      Başsız çalıştırmak için: SSH_SETUP_EMAIL=you@example.com %s' ;;
        key-exists)
            en='Warning: %s already exists.'
            tr='Uyari: %s zaten mevcut.' ;;
        ask-overwrite)
            en='Overwrite it? (e = yes / h = no): '
            tr='Üzerine yazmak istiyor musunuz? (e/h): ' ;;
        cancelled)
            en='Cancelled.'
            tr='İşlem iptal edildi.' ;;
        generating)
            en='Generating the SSH key...'
            tr='SSH key oluşturuluyor...' ;;
        generated)
            en='The SSH key was created.'
            tr='SSH key başarıyla oluşturuldu!' ;;
        config-updated)
            en='SSH config updated.'
            tr='SSH config güncellendi.' ;;
        agent-add-failed)
            en='[Warning: the key could not be added to ssh-agent  -  by hand: ssh-add %s]'
            tr="[Uyari: anahtar ssh-agent'a eklenemedi  -  elle: ssh-add %s]" ;;
        public-key-heading)
            en='  Your public key (this is what goes into GitHub):'
            tr="  Public key'iniz (aşağıdaki GitHub'a eklenecek):" ;;
        clipboard-ok)
            en='[Copied to the clipboard.]'
            tr='[Otomatik olarak panoya kopyalandı!]' ;;
        clipboard-none)
            en='[Could not copy to the clipboard  -  copy the key above by hand]'
            tr='[Panoya kopyalanamadı  -  yukarıdaki anahtarı manuel kopyalayın]' ;;
        next-steps)
            en='=== Next Steps ==='
            tr='=== Sonraki Adımlar ===' ;;
        next-step-1)
            en='1. Go to https://github.com/settings/ssh/new'
            tr='1. https://github.com/settings/ssh/new adresine gidin' ;;
        next-step-2)
            en="2. Give it a name in the 'Title' field (e.g. MacBook)"
            tr="2. 'Title' alanına bir isim verin (ör: MacBook)" ;;
        next-step-3)
            en="3. Paste the copied key into the 'Key' field (Cmd+V)"
            tr="3. 'Key' alanına kopyalanan key'i yapıştırın (Cmd+V)" ;;
        next-step-4)
            en="4. Click the 'Add SSH key' button"
            tr="4. 'Add SSH key' butonuna tıklayın" ;;
        ask-test)
            en='Test the connection now that the key is on GitHub? (e = yes / h = no): '
            tr="Key'i GitHub'a ekledikten sonra test etmek ister misiniz? (e/h): " ;;
        testing)
            en='Testing the GitHub connection...'
            tr='GitHub bağlantısı test ediliyor...' ;;
        finished)
            en='Done.'
            tr='Tamamlandı!' ;;
        *)
            printf 'github-ssh-setup: no message for %s\n' "$key" >&2
            return 1 ;;
    esac
    [ "$OUT_LANG" = tr ] && fmt="$tr" || fmt="$en"
    # shellcheck disable=SC2059
    printf "$fmt\n" "$@"
}

# Soruyu sor, ama yalnız soracak birisi varsa. Terminal yoksa env'deki cevabı
# kullan; o da yoksa boş dön ve kararı çağırana bırak.
ask() {
    local prompt="$1" preset="$2" __var="$3" reply=""
    if [ -n "$preset" ]; then
        printf '%s%s [env]\n' "$prompt" "$preset"
        printf -v "$__var" '%s' "$preset"
        return 0
    fi
    # "Terminal yok" başsızlığın olağan biçimi, tek biçimi değil: screen,
    # tmux ya da bir sunucudaki login kabuğunun terminali VARDIR ve önünde
    # kimse yoktur. MULTI_AGENT_UNATTENDED=1 operatörün bunu açıkça söylemesi;
    # refs/unattended-contract.md. Tanımsızken hiçbir şey değişmez.
    if [ ! -t 0 ] || [ "${MULTI_AGENT_UNATTENDED:-}" = "1" ]; then
        printf -v "$__var" '%s' ""
        return 0
    fi
    # EOF (Ctrl-D) is an answer, not a crash: without `|| true` `set -e`
    # turns a user pressing Ctrl-D into an exit with no message at all.
    read -r -p "$prompt" reply || true
    printf -v "$__var" '%s' "$reply"
}

msg title
echo ""

# E-posta adresi al
ask "$(msg ask-email)" "${SSH_SETUP_EMAIL:-}" EMAIL

if [ -z "$EMAIL" ]; then
    if [ -t 0 ] && [ "${MULTI_AGENT_UNATTENDED:-}" != "1" ]; then
        msg email-empty
    else
        if [ "${MULTI_AGENT_UNATTENDED:-}" = "1" ]; then
            msg email-missing-unattended >&2
        else
            msg email-missing-headless >&2
        fi
        msg headless-hint "$0" >&2
    fi
    exit 1
fi

# Key dosya adı
KEY_NAME="id_ed25519_github"
KEY_PATH="$HOME/.ssh/$KEY_NAME"

# .ssh klasörü yoksa oluştur
mkdir -p "$HOME/.ssh"
chmod 700 "$HOME/.ssh"

# Mevcut key kontrolü
if [ -f "$KEY_PATH" ]; then
    echo ""
    msg key-exists "$KEY_PATH"
    # Varsayılan HAYIR. Başsız bir koşuda cevapsız kalan bir "üzerine yazayım
    # mı" sorusunun güvenli tarafı, var olan anahtarı korumaktır.
    ask "$(msg ask-overwrite)" "${SSH_SETUP_OVERWRITE:-}" OVERWRITE
    if [ "$OVERWRITE" != "e" ]; then
        msg cancelled
        exit 0
    fi
fi

# SSH key oluştur (Ed25519 - modern ve güvenli)
echo ""
msg generating
# ssh-keygen var olan bir dosyayı görünce KENDİ "Overwrite (y/n)?" sorusunu
# sorar - yani yukarıdaki onayı geçtikten sonra başsız koşu ikinci bir
# soruda asılır. Onay zaten alındı; dosyayı önce kaldır.
rm -f "$KEY_PATH" "${KEY_PATH}.pub"
ssh-keygen -t ed25519 -C "$EMAIL" -f "$KEY_PATH" -N "" -q

echo ""
msg generated

# SSH agent'a ekle
eval "$(ssh-agent -s)" > /dev/null 2>&1

# SSH config ayarla (UseKeychain Apple'ın ssh'ına özgü bir seçenek; onu tanımayan
# bir ssh config'i bilinmeyen seçenek diye reddeder)
SSH_CONFIG="$HOME/.ssh/config"
USE_KEYCHAIN_LINE=""
if [ "$(uname -s 2>/dev/null)" = "Darwin" ]; then
    USE_KEYCHAIN_LINE="    UseKeychain yes"
fi
if ! grep -q "github.com" "$SSH_CONFIG" 2>/dev/null; then
    cat >> "$SSH_CONFIG" <<EOF

Host github.com
    HostName github.com
    User git
    IdentityFile $KEY_PATH
    AddKeysToAgent yes
${USE_KEYCHAIN_LINE}
EOF
    chmod 600 "$SSH_CONFIG"
    msg config-updated
fi

# Key'i agent'a ekle (macOS Keychain ile)
# Agent yoksa ekleme başarısız olur; anahtar yazıldıktan sonra bunun için
# çıkmak, kurulumu yarıda bırakıp kullanıcıya hiçbir sonraki adımı
# göstermemek demek.
ssh-add --apple-use-keychain "$KEY_PATH" 2>/dev/null \
  || ssh-add "$KEY_PATH" 2>/dev/null \
  || msg agent-add-failed "$KEY_PATH"

# Public key'i göster ve kopyala
echo ""
echo "================================================"
msg public-key-heading
echo "================================================"
echo ""
cat "${KEY_PATH}.pub"
echo ""

# Panoya kopyala
if command -v pbcopy >/dev/null 2>&1; then
  pbcopy < "${KEY_PATH}.pub"
  msg clipboard-ok
else
  msg clipboard-none
fi

echo ""
msg next-steps
msg next-step-1
msg next-step-2
msg next-step-3
msg next-step-4
echo ""

# GitHub'a key eklendikten sonra test
ask "$(msg ask-test)" "${SSH_SETUP_TEST:-}" TEST
if [ "$TEST" = "e" ]; then
    echo ""
    msg testing
    # Bilinmeyen host anahtarı üçüncü bir interaktif soru demek; başsız
    # koşuda orada asılırdı.
    ssh -o StrictHostKeyChecking=accept-new -T git@github.com 2>&1 || true
fi

echo ""
msg finished
