#!/bin/bash

# Setup keys, psk and config for a central wireguard server including peers

# Dependencies
# apk add wireguard-tools libqrencode

### References
# https://wiki.archlinux.org/title/WireGuard

# Source global variables
confdir='./config'
source ./config/server.cfg

# ---------Functions-----------

## Create key-pair
wgkeypair() { wg genkey | (umask 0077 && tee   $1.key) | wg pubkey > $1.pub; }

## Create psk
wgpsk()     { wg genpsk | (umask 0077 && cat > $1.psk) } 

## Create peer config file
wgconfig() {
  peer=$1
  ip=$2

  cat >$peer.conf <<EOL
# Client config for $peer
[Interface]
PrivateKey = `cat $peer.key`
Address = $ip
DNS = $dns
 
[Peer]
PublicKey = `cat $servername.pub`
AllowedIPs = $network
Endpoint = $servername:$serverport
PersistentKeepalive = 15
PresharedKey = `cat $peer.psk`
EOL

  qrencode  -t ANSI256 -r $peer.conf > $peer-qr.txt
  qrencode  -t png -r $peer.conf -o $peer.png
}


# ---------Functions-----------

## Create and move to output folder
mkdir -p $confdir
cd $confdir

## Create server keys
wgkeypair $servername

## Create server config
cat >$servername.conf <<EOL
# Config for $peer
[Interface]
PrivateKey = `cat $servername.key`
Address = $serverip
DNS = $dns
EOL

## Create peers' key-pair, psk and config from peers.cfg
while read peer;
 do
     ip=`echo $peer | cut -d' ' -f1`
   host=`echo $peer | cut -d' ' -f2`
   
   wgkeypair $host
   wgpsk $host
   wgconfig $host $ip

   # Add peers to server config
      cat >>$servername.conf <<EOL
[Peer]
PublicKey = `cat $host.pub`
AllowedIPs = $ip
PresharedKey = `cat $host.psk`
EOL
 done < peers.cfg