load_keys 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. HOST="${HOST:-$(hostname -s 2>/dev/null || hostname)}"
  4. PASS_BASE="personal/ssh"
  5. STORE_ROOT="${PASSWORD_STORE_DIR:-$HOME/.password-store}"
  6. ABS_BASE_PATH="${STORE_ROOT}/${PASS_BASE}"
  7. # Ensure ssh-agent is running
  8. if [[ -z "${SSH_AUTH_SOCK:-}" ]]; then
  9. eval "$(ssh-agent -s)"
  10. fi
  11. # Verify the base path exists
  12. if [[ ! -d "$ABS_BASE_PATH" ]]; then
  13. echo "ERROR: Base path not found in pass: $PASS_BASE" >&2
  14. exit 1
  15. fi
  16. # Loop through each identity subdirectory
  17. echo -n "Loading ssh keys for host: "
  18. while IFS= read -r dir; do
  19. IDENTITY=$(basename "$dir")
  20. # Find the latest .gpg file by name (ISO sort) and hostname
  21. LATEST_FILE=$(find "$dir" -maxdepth 1 -name "*.gpg" -exec basename {} \; \
  22. | sed 's/\.gpg$//' \
  23. | sort -r \
  24. | head -n 1)
  25. if [[ -z "$LATEST_FILE" ]]; then
  26. continue
  27. fi
  28. echo -n "$HOST"
  29. # Decrypt and pipe directly to ssh-add
  30. # The '-' tells ssh-add to read the key from standard input (stdin)
  31. pass show "${PASS_BASE}/${IDENTITY}/${LATEST_FILE}" | ssh-add - >/dev/null 2>&1
  32. done < <(find "$ABS_BASE_PATH" -mindepth 1 -maxdepth 1 -type d -name "*${HOST}*")