#!/bin/bash

export CLIENT_NAME=$1
export CLIENT_IP_SUFFIX=$2

if [ -z $CLIENT_NAME ];
  then echo 'Client name required. `./add_client.sh client_name 3`';
  exit 1;
fi

if [ -z $CLIENT_IP_SUFFIX ];
  then echo 'Client IP suffix. `./add_client.sh client_name 3`';
  exit 1;
fi

export SERVER_PUBKEY=$(cat /etc/wireguard/publickey)
mkdir /etc/wireguard/$CLIENT_NAME
cd /etc/wireguard/$CLIENT_NAME
export PRIVKEY=$(wg genkey)
echo $PRIVKEY | tee $CLIENT_NAME"_privkey"
export PUBKEY=$(echo $PRIVKEY | wg pubkey)
echo $PUBKEY | tee $CLIENT_NAME"_pubkey"

cat > $CLIENT_NAME".conf" <<EOF
[Interface]
PrivateKey = $PRIVKEY
Address = 10.10.0.$CLIENT_IP_SUFFIX/32, fd86:ea04:1111::$CLIENT_IP_SUFFIX/128
DNS = 1.1.1.1,1.0.01

[Peer]
PublicKey = $SERVER_PUBKEY
Endpoint = yellow.reeselink.com:51820
AllowedIPs = 0.0.0.0/0, ::/0
EOF

wg set wg0 peer $PUBKEY allowed-ips 10.10.0.$CLIENT_IP_SUFFIX/32,fd86:ea04:1111::$CLIENT_IP_SUFFIX/128
wg-quick save wg0
