#!/bin/bash

set -e

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

print_error() {
    echo -e "${RED}ERROR: $1${NC}" >&2
}

print_success() {
    echo -e "${GREEN}SUCCESS: $1${NC}"
}

print_info() {
    echo -e "${YELLOW}INFO: $1${NC}"
}

# GPG Key ID
GPG_KEY_ID="0F23ABFF8F00056D52F1A82E4A72C4B48B15B19F"

echo "============================================"
echo "GPG Key Self-Signature Refresh Script"
echo "============================================"
echo ""

print_info "This script will refresh the self-signature of your GPG key with SHA512."
echo ""

# Check if the key exists
if ! gpg --list-secret-keys "$GPG_KEY_ID" &> /dev/null; then
    print_error "GPG key $GPG_KEY_ID not found in your keyring!"
    exit 1
fi

print_info "Found GPG key: $GPG_KEY_ID"

# Create a stronger GPG configuration
print_info "Setting up secure GPG configuration..."
mkdir -p ~/.gnupg

# Backup current GPG configuration
if [ -f ~/.gnupg/gpg.conf ]; then
    print_info "Backing up current GPG configuration..."
    cp ~/.gnupg/gpg.conf ~/.gnupg/gpg.conf.backup.$(date +%Y%m%d-%H%M%S)
fi

# Create secure configuration
cat > ~/.gnupg/gpg.conf << 'EOF'
# Use SHA512 for signatures
cert-digest-algo SHA512
digest-algo SHA512
personal-digest-preferences SHA512 SHA384 SHA256
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed

# Strong key preferences
personal-cipher-preferences AES256 AES192 AES
personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed

# Display long key IDs and fingerprints
keyid-format 0xlong
with-fingerprint
EOF

print_success "Secure GPG configuration applied"

# Export the private key
print_info "Exporting private key..."
gpg --export-secret-keys "$GPG_KEY_ID" > /tmp/key-backup.gpg

# Method 1: Try using gpg directly to refresh the binding signature
print_info "Method 1: Attempting to refresh self-signature directly..."

# Create a GPG command script to automate the process
cat > /tmp/gpg-refresh-commands << EOF
passwd
save
EOF

print_info "Refreshing key self-signature (this updates the binding signatures with SHA512)..."
echo "" | gpg --command-file /tmp/gpg-refresh-commands --expert --edit-key "$GPG_KEY_ID" 2>/dev/null || true

# Clean up
rm -f /tmp/gpg-refresh-commands

# Method 2: If the above doesn't work, try quick-set-expire
print_info "Method 2: Using quick-set-expire to refresh signatures..."

# Get key expiration (or set to 5 years if no expiration)
CURRENT_EXPIRE=$(gpg --list-secret-keys --with-colons "$GPG_KEY_ID" | grep "^sec" | cut -d: -f7)
if [ -z "$CURRENT_EXPIRE" ]; then
    NEW_EXPIRE="5y"
else
    NEW_EXPIRE="5y"
fi

# Set expiration (this forces a new self-signature with current hash preferences)
print_info "Setting key expiration to force new self-signature..."
gpg --quick-set-expire "$GPG_KEY_ID" "$NEW_EXPIRE"

print_success "Key self-signature refreshed with SHA512"

# Export the updated key
print_info "Exporting updated public key..."
gpg --armor --export "$GPG_KEY_ID" > evebox-repo.asc

print_success "Updated public key exported to evebox-repo.asc"

# Verify the update
print_info "Verifying the updated key..."
echo ""
echo "Key hash preferences:"
gpg --list-key --with-pref-verbose "$GPG_KEY_ID" | grep -A2 "Hash:"

echo ""
print_success "Key signature refresh complete!"
echo ""
echo "Next steps:"
echo "1. Re-sign your repository distributions:"
echo "   reprepro export stable"
echo "   reprepro export unstable"
echo ""
echo "2. Upload the new evebox-repo.asc to your web server"
echo ""
echo "3. Have clients re-import the updated key"

# Backup info
print_info "Your original key was backed up to /tmp/key-backup.gpg"
print_info "You can delete it once you've verified everything works: rm /tmp/key-backup.gpg"