#!/bin/sh
if [ -z "$1" ]; then
  echo "Usage: $0 <client-name>"
  exit 1
fi

mkdir -p /etc/wireguard/clients/keys

# Count existing clients to assign next IP, starting from 10.0.0.2
CLIENT_COUNT=$(ls /etc/wireguard/clients | wc -l)
NEXT_IP="10.0.0.$((CLIENT_COUNT + 1))"
CLIENT_NAME=$1
SERVER_ADDRESS="goofjes.nl"

# Generate public and private keys for the client
wg genkey | tee /etc/wireguard/clients/keys/$CLIENT_NAME.priv.key | wg pubkey > /etc/wireguard/clients/keys/$CLIENT_NAME.pub.key

# Generate PSK for the client
wg genpsk | tee /etc/wireguard/clients/keys/$CLIENT_NAME.psk.key

cat <<EOF >> /etc/wireguard/wg0.conf
[Peer]
PublicKey = $(cat /etc/wireguard/clients/keys/$CLIENT_NAME.pub.key)
PresharedKey = $(cat /etc/wireguard/clients/keys/$CLIENT_NAME.psk.key)
AllowedIPs = $NEXT_IP/32
EOF

cat <<EOF > /etc/wireguard/clients/$CLIENT_NAME.conf
[Interface]
Address = $NEXT_IP/24
PrivateKey = $(cat /etc/wireguard/clients/keys/$CLIENT_NAME.priv.key)
DNS = 10.0.0.1 # DNS via the VPN

# $CLIENT_NAME configuration
[Peer]
PublicKey = $(cat /etc/wireguard/server_pub.key)
PresharedKey = $(cat /etc/wireguard/clients/keys/$CLIENT_NAME.psk.key)
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = $SERVER_ADDRESS:51820
EOF

rc-service wg-quick.wg0 restart