#!/bin/bash
# @desc Wireguard client config generator
SERVER_CONF='/etc/wireguard/wg0.conf' 
SERVER_PUBLIC_KEY="$(grep PrivateKey $SERVER_CONF |cut -d= -f2-|tr -d '[:blank:]'|wg pubkey)"
SERVER_ENDPOINT= example.com
CLIENT_IP="10.0.0.$1"

CONFNAME=$(basename "$SERVER_CONF")
IFNAME=${CONFNAME%.conf}
CLIENT_PRIVATE_KEY="$(wg genkey)"
CLIENT_PUBLIC_KEY="$(echo -n $CLIENT_PRIVATE_KEY| wg pubkey)"
CLIENTCONF=client$1.conf
CLIENTUSER="${2:-root}"
cat > $CLIENTCONF << WGCLIENT
[Interface]
Address = $CLIENT_IP/24
PrivateKey = $CLIENT_PRIVATE_KEY

[Peer]
PublicKey = $SERVER_PUBLIC_KEY
Endpoint = $SERVER_ENDPOINT:51820
AllowedIPs = 10.0.0.0/24
WGCLIENT
chown $CLIENTUSER:$CLIENTUSER $CLIENTCONF
chmod 600 $CLIENTCONF
CLIENT_CONFPATH=$(getent passwd "$CLIENTUSER"| cut -d: -f6)
[ "$CLIENTCONF" -ef "$CLIENT_CONFPATH/$CLIENTCONF" ] || mv -f $CLIENTCONF $CLIENT_CONFPATH

cat >> $SERVER_CONF << WGSERVER
[Peer]
PublicKey = $CLIENT_PUBLIC_KEY
AllowedIPs = $CLIENT_IP
WGSERVER

systemctl reload wg-quick@$IFNAME 
