#!/bin/bash

set -e

usage() {
    echo "Usage: $0 --comment <comment> [--filename <filename>]"
    echo "  --comment <comment>   The comment for the SSH key."
    echo "  --filename <filename> (optional) The filename suffix for the SSH key. Defaults to 'id_ed25519'."
    exit 1
}

# Default values
COMMENT=""
FILENAME="id_ed25519"

# Parse named arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --comment)
            COMMENT="$2"
            shift 2
            ;;
        --filename)
            FILENAME="id_ed25519_$2"
            shift 2
            ;;
        *)
            echo "Unknown argument: $1"
            usage
            ;;
    esac
done

# Validate required arguments
if [ -z "$COMMENT" ]; then
    echo "Error: --comment is required."
    usage
fi

SSH_DIR="$HOME/.ssh"
KEY_PATH="$SSH_DIR/$FILENAME"

# Ensure SSH directory exists
mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"

# Generate SSH key
if [ -f "$KEY_PATH" ]; then
    echo "Skipping: Key file $KEY_PATH already exists."
    exit 0
fi

ssh-keygen -t ed25519 -C "$COMMENT" -f "$KEY_PATH" -N ""

echo "SSH key created at: $KEY_PATH"
echo "Public key:"
cat "$KEY_PATH.pub"
