#!/bin/bash
# Delete a GPG key (both secret and public)
# Usage: gpg-delete-key [key-id or email]

set -e

KEY_ID="${1:-}"

# If no key specified, show available keys and prompt
if [[ -z $KEY_ID ]]; then
    echo "Available GPG keys:"
    echo ""
    gpg --list-secret-keys --keyid-format LONG 2>/dev/null || echo "No keys found"
    echo ""
    read -p "Enter key ID or email to delete: " KEY_ID

    if [[ -z $KEY_ID ]]; then
        echo "No key specified. Aborting."
        exit 1
    fi
fi

# Get the full key fingerprint
FINGERPRINT=$(gpg --list-secret-keys --with-colons "$KEY_ID" 2>/dev/null | grep '^fpr' | head -1 | cut -d: -f10)

if [[ -z $FINGERPRINT ]]; then
    echo "Error: Key not found: $KEY_ID"
    exit 1
fi

echo "Key to delete:"
echo ""
gpg --list-keys --keyid-format LONG "$KEY_ID"
echo ""

echo "WARNING: This will permanently delete the secret and public key!"
read -p "Are you sure? Type 'yes' to confirm: " CONFIRM

if [[ $CONFIRM != "yes" ]]; then
    echo "Aborting."
    exit 1
fi

echo ""
echo "Deleting secret key..."
gpg --batch --yes --delete-secret-keys "$FINGERPRINT"

echo "Deleting public key..."
gpg --batch --yes --delete-keys "$FINGERPRINT"

echo ""
echo "Key deleted successfully."
