#!/usr/bin/with-contenv bash

echo "******* This script has been deprecated and will be removed in a future version. In order to add peers, change the PEERS env var and recreate your container. Existing peers will still use the same private and public keys. *******"

if [ ! -f /config/wg0.conf ] || [ -z "$PEERS" ]; then
  echo "Wireguard is not set up in server mode"
  exit 0
fi

INTERNAL_SUBNET=${INTERNAL_SUBNET:-10.13.13.0}
INTERFACE=$(echo "$INTERNAL_SUBNET" | awk 'BEGIN{FS=OFS="."} NF--')
if [ -z "$SERVERURL" ] || [ "$SERVERURL" = "auto" ]; then
  SERVERURL=$(curl icanhazip.com)
fi
SERVERPORT=${SERVERPORT:-51820}
if [ -z "$PEERDNS" ] || [ "$PEERDNS" = "auto" ]; then
  PEERDNS="${INTERFACE}.1"
fi

for i in {1..254}; do
  if grep -q "AllowedIPs = ${INTERFACE}.$(( $i + 1 ))/32" /config/wg0.conf; then
    echo "Peer $i exists"
  else
    echo "Adding new Peer $i"
    mkdir -p /config/peer${i}
    if [ ! -f /config/peer${i}/privatekey-peer${i} ]; then
      umask 077
      wg genkey | tee /config/peer${i}/privatekey-peer${i} | wg pubkey > /config/peer${i}/publickey-peer${i}
    fi
    eval "`printf %s`
    cat <<DUDE > /config/peer${i}/peer${i}.conf
`cat /config/templates/peer.conf`
DUDE"
    cat <<DUDE >> /config/wg0.conf
[Peer]
PublicKey = $(cat /config/peer${i}/publickey-peer${i})
AllowedIPs = ${INTERFACE}.$(( $i + 1 ))/32

DUDE
    echo "PEER ${i} QR code:"
    qrencode -t ansiutf8 < /config/peer${i}/peer${i}.conf
    qrencode -o /config/peer${i}/peer${i}.png < /config/peer${i}/peer${i}.conf
    chown -R abc:abc /config/peer${i}
    s6-svc -t /var/run/s6/services/wireguard
    break
  fi
done
