#!/usr/bin/env bash
set -euo pipefail
source "$stpRoot/lib/log.sh"
source "$stpRoot/lib/utils.sh"

readonly claudeCodeKeyring="/etc/apt/keyrings/claude-code.asc"
readonly claudeCodeSources="/etc/apt/sources.list.d/claude-code.list"
readonly claudeCodeSourcesEntry="deb [signed-by=${claudeCodeKeyring}] https://downloads.claude.ai/claude-code/apt/stable stable main"

repoIsConfigured() {
    [[ -f "$claudeCodeSources" ]]
}

addSigningKey() {
    sudo install -m 644 "$stpRoot/config/keys/claude-code.asc" "$claudeCodeKeyring"
    log::ok "Clave GPG instalada: $claudeCodeKeyring"
}

addRepository() {
    echo "$claudeCodeSourcesEntry" | sudo tee "$claudeCodeSources" > /dev/null
    sudo apt-get update -qq
    log::ok "Repositorio configurado: $claudeCodeSources"
}

if repoIsConfigured; then
    log::info "Repositorio claude-code ya configurado"
else
    addSigningKey
    addRepository
fi

if util::isAptInstalled "claude-code"; then
    log::info "Ya instalado (apt): claude-code"
else
    sudo apt-get install -y claude-code
    log::ok "Instalado: claude-code"
fi
