#!/bin/bash
set -e

### AUTO CONFIG
WG_IF="wg0"
WG_NET="10.66.66.0/24"
WG_SERVER_IP="10.66.66.1"
WG_CLIENT_IP="10.66.66.2"
WG_PORT=$(shuf -i20000-60000 -n1)
PUB_IF=$(ip route get 8.8.8.8 | awk '{print $5; exit}')

### OS DETECT
if [ -f /etc/debian_version ]; then
  PM="apt"
elif [ -f /etc/redhat-release ]; then
  PM="yum"
else
  echo "Unsupported OS"
  exit 1
fi

echo "[+] Installing packages..."
$PM update -y
$PM install -y wireguard iptables curl qrencode

echo "[+] Generating keys..."
umask 077
wg genkey | tee /etc/wireguard/server.key | wg pubkey > /etc/wireguard/server.pub
wg genkey | tee /etc/wireguard/client.key | wg pubkey > /etc/wireguard/client.pub

SERVER_PRIV=$(cat /etc/wireguard/server.key)
SERVER_PUB=$(cat /etc/wireguard/server.pub)
CLIENT_PRIV=$(cat /etc/wireguard/client.key)
CLIENT_PUB=$(cat /etc/wireguard/client.pub)

echo "[+] Creating server config..."
cat > /etc/wireguard/${WG_IF}.conf <<EOF
[Interface]
Address = ${WG_SERVER_IP}/24
ListenPort = ${WG_PORT}
PrivateKey = ${SERVER_PRIV}
PostUp = iptables -t nat -A POSTROUTING -s ${WG_NET} -o ${PUB_IF} -j MASQUERADE
PostDown = iptables -t nat -D POSTROUTING -s ${WG_NET} -o ${PUB_IF} -j MASQUERADE

[Peer]
PublicKey = ${CLIENT_PUB}
AllowedIPs = ${WG_CLIENT_IP}/32
EOF

echo "[+] Enabling IP Forward..."
sysctl -w net.ipv4.ip_forward=1 >/dev/null
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf

echo "[+] Starting WireGuard..."
systemctl enable wg-quick@${WG_IF} >/dev/null
systemctl start wg-quick@${WG_IF}

SERVER_IP=$(curl -s ifconfig.me)

echo "[+] Creating client config..."
cat > /root/wg-client.conf <<EOF
[Interface]
PrivateKey = ${CLIENT_PRIV}
Address = ${WG_CLIENT_IP}/24
DNS = 1.1.1.1

[Peer]
PublicKey = ${SERVER_PUB}
Endpoint = ${SERVER_IP}:${WG_PORT}
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
EOF

echo ""
echo "=============================="
echo "✅ AUTO PILOT DONE"
echo "🌐 Server IP : ${SERVER_IP}"
echo "🔐 Port      : ${WG_PORT}"
echo "📄 Client    : /root/wg-client.conf"
echo "📱 QR Code:"
echo "=============================="
qrencode -t ansiutf8 < /root/wg-client.conf
