#!/bin/bash

apt update
apt install -y wireguard


echo "====生成wireguard密钥对..."
umask 077
wg genkey | tee /etc/wireguard/privatekey | wg pubkey > /etc/wireguard/publickey
PRIVATE_KEY=$(< /etc/wireguard/privatekey)
PUBLIC_KEY=$(< /etc/wireguard/publickey)

read -p "请输入Wireguard客户端IP地址,格式: [10.0.0.1/24] :" server_ip

echo "====生成wireguard配置文件..."
cat << ENOF > /etc/wireguard/wg0.conf
[Interface]
Address = $server_ip
PrivateKey = $PRIVATE_KEY
Table = off

[Peer]
PublicKey = tLML+XZpp10/CLSMdb3/zjteJauWunWoeFdnc5TYtwI=
Endpoint = 199.188.74.31:6666
AllowedIPs = 0.0.0.0/0,::/0
PersistentKeepalive = 25
ENOF

echo "====启动wireguard服务..."
wg-quick up wg0

echo "====配置iptables..."
read -p "QEMU虚拟网桥网段,格式: [10.20.110.1/25] :" br0_net
iptables -t mangle -A PREROUTING -s $br0_net -j MARK --set-mark 10
sleep 1
ip rule add from all fwmark 10 table 10
sleep 1
ip route add default via 10.0.1.1 table 10

# 编辑 /etc/sysctl.conf 文件以启用 IP 转发
# 使用 echo 命令追加文本到文件中，如果文件中已经存在该行则不重复添加
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf

# 使用 sysctl -p 应用 /etc/sysctl.conf 中的更改
sysctl -p

# 检查 IP 转发是否已启用
if sysctl net.ipv4.ip_forward | grep -q "net.ipv4.ip_forward = 1"; then
    echo "IP forwarding enabled successfully."
else
    echo "Failed to enable IP forwarding."
fi


wg_config=$(cat <<EOF
[Peer]
PublicKey = $PUBLIC_KEY
AllowedIPs = $server_ip,$br0_net
EOF
)
echo $wg_config > /etc/wireguard/gateway.conf

machine_id=$(cat /etc/machine-id)
echo "============================================"
echo "machine-id:$machine_id"
echo "============================================"
echo "Public Key:$PUBLIC_KEY"
echo "============================================"
echo $wg_config
echo "============================================"

echo "***********网络配置完成！***************"

rm -rf ./network.sh