#!/bin/bash
# 获取所有 WireGuard 接口的公钥

echo "🔑 获取所有 WireGuard 接口的公钥"
echo "================================"

# 查找所有 WireGuard 配置文件
CONFIG_FILES=$(find /etc/wireguard -name "*.conf" -type f)

if [ -z "$CONFIG_FILES" ]; then
    echo "❌ 未找到任何 WireGuard 配置文件"
    exit 1
fi

echo "找到以下 WireGuard 配置文件:"
echo ""

for CONFIG_FILE in $CONFIG_FILES; do
    INTERFACE_NAME=$(basename "$CONFIG_FILE" .conf)
    echo "接口: $INTERFACE_NAME"
    echo "配置文件: $CONFIG_FILE"
    
    # 尝试从配置文件获取公钥
    if grep -q '^PrivateKey' "$CONFIG_FILE"; then
        PRIVATE_KEY=$(grep '^PrivateKey' "$CONFIG_FILE" | cut -d= -f2 | tr -d ' ')
        PUBLIC_KEY=$(echo "$PRIVATE_KEY" | wg pubkey)
        echo "公钥: $PUBLIC_KEY"
    elif [ -f "/etc/wireguard/${INTERFACE_NAME}.key" ]; then
        # 尝试从单独的密钥文件获取
        PRIVATE_KEY=$(cat "/etc/wireguard/${INTERFACE_NAME}.key" | tr -d ' \n\r')
        PUBLIC_KEY=$(echo "$PRIVATE_KEY" | wg pubkey)
        echo "公钥: $PUBLIC_KEY"
    else
        echo "❌ 无法获取公钥"
    fi
    echo "----------------------------------------"
done