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

readonly sshDestination="$HOME/.ssh"
readonly encryptedArchive="$stpRoot/secrets/sshKeys.tar.gz.age"

sshPermissionsForFile() {
    local keyFilename="$1"
    case "$keyFilename" in
        *.pub|known_hosts|config) echo 644 ;;
        *) echo 600 ;;
    esac
}

ensureSshDirectoryExists() {
    if [[ ! -d "$sshDestination" ]]; then
        mkdir -p "$sshDestination"
        chmod 700 "$sshDestination"
    fi
}

decryptArchiveInto() {
    local workingDirectory="$1"
    log::info "Ingresá la passphrase para descifrar las claves SSH:"
    if ! age -d -o "$workingDirectory/sshKeys.tar.gz" "$encryptedArchive"; then
        log::error "Error al descifrar. Verificá la passphrase."
        return 1
    fi
    tar -xzf "$workingDirectory/sshKeys.tar.gz" -C "$workingDirectory"
}

installSshKey() {
    local sourceFile="$1"
    local keyFilename
    keyFilename="$(basename "$sourceFile")"
    local destination="$sshDestination/$keyFilename"

    if [[ -f "$destination" ]]; then
        log::warn "Ya existe (salteando): $keyFilename"
        return 1
    fi

    cp "$sourceFile" "$destination"
    chmod "$(sshPermissionsForFile "$keyFilename")" "$destination"
    log::ok "Instalada: $keyFilename"
}

installAllKeysFrom() {
    local sourceDirectory="$1"
    local installedCount=0 skippedCount=0

    for sourceFile in "$sourceDirectory/.ssh/"*; do
        [[ -f "$sourceFile" ]] || continue
        if installSshKey "$sourceFile"; then
            ((++installedCount))
        else
            ((++skippedCount))
        fi
    done

    log::ok "$installedCount clave(s) instaladas, $skippedCount salteada(s)"
}

if [[ ! -f "$encryptedArchive" ]]; then
    log::warn "Archivo de claves no encontrado: secrets/sshKeys.tar.gz.age"
    log::warn "Para cifrar tus claves actuales: bash scripts/encryptSsh.sh"
    exit 0
fi

if ! util::cmdExists age; then
    log::error "age no está instalado. Ejecutá primero el módulo bootstrap"
    exit 1
fi

log::info "Restaurando claves SSH..."

workingDirectory="$(mktemp -d)"
trap 'rm -rf "$workingDirectory"' EXIT

decryptArchiveInto "$workingDirectory"
ensureSshDirectoryExists
installAllKeysFrom "$workingDirectory"
