#!/bin/sh set -e die() { echo "$*" 1>&2 exit 1 } [ -z "$1" ] && die "usage: $0 HOST" NAME="$1" DATADIR=${DATADIR:-/etc/wg} HOSTFILE=${HOSTFILE:-${DATADIR}/hosts} # Detect if name in use if grep -q "^$NAME[[:space:]]" "$HOSTFILE"; then die "hostname $NAME taken" fi # Get public and private keys CONF="$DATADIR/$NAME" mkdir -p "$CONF" openssl rand -base64 32 > "$CONF/private.key" ifconfig wg9 destroy 2>/dev/null || true ifconfig wg9 create wgport 13421 wgkey "$(cat "$CONF/private.key")" ifconfig wg9 | grep wgpubkey | cut -d ' ' -f 2 > "$CONF/public.key" ifconfig wg9 destroy 2>/dev/null || true # Assign an IP CUR=$(tail -n 1 "$HOSTFILE" | cut -d. -f 4) NEXT=$((CUR + 1)) echo "$NAME 10.6.6.$NEXT" >> "$HOSTFILE" # Generate the config cat < "$CONF/client.conf" # public key: $(cat "$CONF/public.key") [Interface] PrivateKey = $(cat "$CONF/private.key") Address = 10.6.6.$NEXT/24 [Peer] PublicKey = JpsSfrcrhCcTR5bybV9YQaAV60A12heinyAiSbMK3ng= AllowedIPs = 10.6.6.1/32 Endpoint = 45.79.221.98:7149 EOM # Lastly, append to /etc/hostname.wg0 and restart it cat <> /etc/hostname.wg0 wgpeer $(cat "$CONF/public.key") wgaip 10.6.6.$NEXT/32 EOM sh /etc/netstart