#!/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 SHA1 Fix Script"
echo "============================================"
echo ""

print_info "This script will help fix the SHA1 signature issue with your GPG key."
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 "Creating secure GPG configuration..."
cat > ~/.gnupg/gpg.conf.secure << 'EOF'
# Use SHA512 for signatures
cert-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

# Disable weak algorithms
weak-digest SHA1
EOF

# 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

# Apply secure configuration
cp ~/.gnupg/gpg.conf.secure ~/.gnupg/gpg.conf

print_success "Secure GPG configuration applied"

echo ""
echo "Now you have two options to fix the SHA1 issue:"
echo ""
echo "OPTION 1: Update the existing key (Recommended)"
echo "================================================"
echo "Run these commands to update your key's self-signature:"
echo ""
echo "  # Edit the key"
echo "  gpg --expert --edit-key $GPG_KEY_ID"
echo ""
echo "  # In the GPG prompt, run these commands:"
echo "  gpg> clean"
echo "  gpg> minimize"
echo "  gpg> save"
echo ""
echo "  # Then re-sign the key with SHA512:"
echo "  gpg --expert --edit-key $GPG_KEY_ID"
echo "  gpg> sign"
echo "  gpg> save"
echo ""
echo "  # Export the updated key:"
echo "  gpg --armor --export $GPG_KEY_ID > evebox-repo.asc"
echo ""
echo "OPTION 2: Create a new signing key"
echo "==================================="
echo "Run: ./create-new-signing-key.sh"
echo ""

# Create script for new key generation
cat > create-new-signing-key.sh << 'EOF'
#!/bin/bash

set -e

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

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

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

print_info "Generating new GPG key for repository signing with SHA512..."

# Generate new key with strong defaults
cat > gpg-batch-secure << 'EOFBATCH'
%echo Generating secure EveBox repository signing key
Key-Type: RSA
Key-Length: 4096
Subkey-Type: RSA
Subkey-Length: 4096
Name-Real: EveBox Repository
Name-Email: repo@evebox.org
Expire-Date: 5y
Preferences: SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
%no-protection
%commit
%echo done
EOFBATCH

gpg --batch --generate-key gpg-batch-secure
rm gpg-batch-secure

# Get the new key ID
NEW_KEY_ID=$(gpg --list-secret-keys --keyid-format=long | grep -A1 "EveBox Repository" | grep "sec" | awk '{print $2}' | cut -d'/' -f2)

print_success "New GPG key generated: $NEW_KEY_ID"

# Export the new key
gpg --armor --export "$NEW_KEY_ID" > evebox-repo-new.asc

print_success "New public key exported to evebox-repo-new.asc"

echo ""
echo "Next steps:"
echo "1. Update conf/distributions to use the new key ID: $NEW_KEY_ID"
echo "2. Replace evebox-repo.asc with evebox-repo-new.asc"
echo "3. Re-sign your repository packages with: reprepro export"
echo ""
echo "Update conf/distributions with:"
echo "  sed -i 's/SignWith: .*/SignWith: $NEW_KEY_ID/' conf/distributions"
EOF

chmod +x create-new-signing-key.sh

print_success "Script created: create-new-signing-key.sh"

echo ""
echo "After fixing the key, you'll need to:"
echo "1. Re-export all repository distributions:"
echo "   reprepro export stable"
echo "   reprepro export unstable"
echo "2. Update the public key on your web server"
echo "3. Have clients re-import the updated key"