#!/bin/bash # tin key generate - Generate SSH key for NAS server set -euo pipefail # Get tinsnip root and source libraries SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" TINSNIP_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")" source "$TINSNIP_ROOT/lib/core.sh" source "$TINSNIP_ROOT/lib/registry.sh" # Generate SSH key pair for a NAS server generate_nas_key() { local nas_server="$1" check_tinsnip_station || return 1 # Ensure the ssh-keys directory exists local ssh_keys_dir="$NAS_CREDENTIALS_DIR/ssh-keys" if [[ ! -d "$ssh_keys_dir" ]]; then log_with_prefix "SSH Keys" "Creating SSH keys directory: $ssh_keys_dir" mkdir -p "$ssh_keys_dir" fi local key_path="$ssh_keys_dir/${nas_server}.key" local pub_key_path="${key_path}.pub" if [[ -f "$key_path" ]]; then warn_with_prefix "SSH Keys" "SSH key already exists for $nas_server" echo -e "\033[1;36mOverwrite existing key? [y/N]: \033[0m\c" read overwrite case "$overwrite" in [Yy]*) log_with_prefix "SSH Keys" "Overwriting existing key for $nas_server" rm -f "$key_path" "$pub_key_path" ;; *) log_with_prefix "SSH Keys" "Keeping existing key for $nas_server" return 0 ;; esac fi log_with_prefix "SSH Keys" "Generating SSH key for NAS server: $nas_server" # Generate key with no passphrase for automation ssh-keygen -t ed25519 \ -f "$key_path" \ -C "tinsnip@$(hostname)-$nas_server" \ -N "" \ -q # Set restrictive permissions chmod 600 "$key_path" chmod 644 "$pub_key_path" log_with_prefix "SSH Keys" "SSH key generated: $key_path" log_with_prefix "SSH Keys" "Public key: $pub_key_path" log_with_prefix "SSH Keys" "✅ SSH key generated successfully" log_with_prefix "Next Steps" "Install on NAS: tin key install $nas_server" return 0 } show_help() { cat << EOF tin key generate - Generate SSH key for NAS server USAGE: tin key generate tin key # Shorthand DESCRIPTION: Generate an SSH key pair for authenticating with a NAS server. Keys are stored in the tinsnip station for centralized management and can be installed on the NAS for password-free access. ARGUMENTS: NAS server hostname or IP address EXAMPLES: tin key generate DS412plus.local # Generate key for DS412plus tin key 192.168.1.100 # Generate key for NAS IP tin key mynas # Generate key for named server NOTES: - Keys are stored in /mnt/station-prod/data/nas-credentials/ssh-keys/ - Use 'tin key install ' to install the key on the NAS - Use 'tin key list' to see generated keys EOF } # Handle help flags case "${1:-}" in --help|-h|help) show_help exit 0 ;; esac # Main execution if [[ $# -eq 0 ]]; then error_with_prefix "Key Generate" "NAS server name required" echo "Usage: tin key generate " >&2 exit 1 fi nas_server="$1" # Validate NAS server name (basic validation) if [[ -z "$nas_server" ]]; then error_with_prefix "Key Generate" "NAS server name cannot be empty" fi generate_nas_key "$nas_server"