#!/usr/bin/env bash
# fn_sync_with_pass — Wrapper de fn sync que lee credenciales desde pass.
set -euo pipefail

FN_ROOT="${FN_REGISTRY_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"

fn_sync_with_pass() {
    command -v pass >/dev/null 2>&1 || {
        echo "fn_sync_with_pass: 'pass' CLI no instalado. Instala con: apt install pass" >&2
        return 127
    }

    local u p t

    u=$(pass show registry/basicauth-user 2>/dev/null | head -n1) || {
        echo "fn_sync_with_pass: falta registry/basicauth-user en pass. Crea con: pass insert registry/basicauth-user" >&2
        return 1
    }
    p=$(pass show registry/basicauth-pass 2>/dev/null | head -n1) || {
        echo "fn_sync_with_pass: falta registry/basicauth-pass en pass. Crea con: pass insert registry/basicauth-pass" >&2
        return 1
    }
    t=$(pass show registry/api-token 2>/dev/null | head -n1) || {
        echo "fn_sync_with_pass: falta registry/api-token en pass. Crea con: pass insert registry/api-token" >&2
        return 1
    }

    export FN_REGISTRY_API="https://${u}:${p}@registry.organic-machine.com"
    export REGISTRY_API_TOKEN="$t"

    cd "$FN_ROOT"
    ./fn sync "$@"
}

# Ejecucion directa (no library mode)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    fn_sync_with_pass "$@"
fi
