From ead88b2a384e46b940d0d6cecf621cfc6b7ef0b6 Mon Sep 17 00:00:00 2001
From: coolneng <akasroua@gmail.com>
Date: Sun, 1 Aug 2021 18:27:50 +0100
Subject: [PATCH] Add automatic generation of VPN config to script

---
 vpn-client.sh | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)

diff --git a/vpn-client.sh b/vpn-client.sh
index 78ee6a0..f13dd34 100755
--- a/vpn-client.sh
+++ b/vpn-client.sh
@@ -6,10 +6,34 @@ usage() {
     exit 1
 }
 
+get_last_ip() {
+    last_ocurrence=$(grep '10.9.0' "$networking_file" | tail -1)
+    last_digit=$(echo "$last_ocurrence" | cut -d . -f 4 | cut -c 1)
+}
+
+generate_certificates() {
+    mkdir "$certificates_directory/$hostname"
+    cd "$certificates_directory/$hostname" || exit
+    wg genkey | tee "$hostname".key | wg pubkey >"$hostname".pub
+}
+
+generate_config() {
+    private_key=$(cat "$hostname.key")
+    get_last_ip
+    last_ip=$((last_digit + 1))
+    cd "$config_directory" || exit
+    sed -e "s/private_key_placeholder/$private_key/g" -e "s/ip_placeholder/$last_ip/g" "$config_file" >"$hostname".conf
+}
+
 if [ $# != 1 ]; then
     usage
 fi
 
 hostname=$1
+networking_file="/etc/nixos/modules/networking.nix"
+certificates_directory="/home/coace/.wg"
+config_directory="/vault/config/wireguard"
+config_file="$config_directory/placeholder.conf"
 
-wg genkey | tee "$hostname".key | wg pubkey >"$hostname".pub
+generate_certificates
+generate_config