#!/usr/bin/env bash

set -e

wg_server_pubkey=$(wg genkey | tee server-private.key | wg pubkey)

client_count=0

config_file=wg-$(echo $RANDOM | sha256sum | head -c 8).conf
server_config_file=server-${config_file}
random_port=$(echo $[$RANDOM % 65535 + 4096])

print_client_config() {
	for (( i=1; i<=${client_count}; i++ )); do
		local wg_client_pubkey=$(wg genkey | tee client${i}-private.key | wg pubkey)
		local wg_client_privkey=$(cat client${i}-private.key)
		local client_config_file=client${i}-${config_file}

		echo
		read -p "> [+] Enter client [${i}]'s IP (Default: 192.168.1.${i}/32): " client_ip
		read -p "> [+] Enter client [${i}]'s endpoint: " endpoint
		read -p "> [+] Enter client [${i}]'s DNS (Default: 127.0.0.1): " dns
		read -p "> [+] Enter client [${i}]'s AllowedIPs (Default: 0.0.0.0/0, ::/0): " allowed_ips
		read -p "> [+] Enter client [${i}]'s PersistentKeepalive (Default: 25): " persistent_keep_alive

		cat <<-EOF > ${client_config_file}
			# Client ${i} config

			[Interface]
			PrivateKey = ${wg_client_privkey}
			Address = ${client_ip:="192.168.1.${i}/32"}
			DNS = ${dns:=127.0.0.1}

			[Peer]
			PublicKey = ${wg_server_pubkey}
			Endpoint = ${endpoint}:${random_port}
			AllowedIPs = ${allowed_ips:="0.0.0.0/0, ::/0"}
			PersistentKeepalive = ${persistent_keep_alive:=25}
		EOF

		cat <<-EOF >> ${server_config_file}

			# Client ${i}
			[Peer]
			PublicKey = ${wg_client_pubkey}
			AllowedIPs = ${client_ip:="192.168.1.${i}/32"}
		EOF

		read -p "> [+] Would you like to show client [${i}]'s QR configuration (y/N): " show_qr
		if [[ ${show_qr} == 'y' || ${show_qr} == 'Y' ]]; then
			clear
			qrencode -t ansiutf8 < ${client_config_file}

			echo ""
			echo "> [+] Press Enter to continue . . ."
			read
		fi
	done
}

print_server_config() {
	local wg_server_privkey=$(cat server-private.key)

	read -p "> [+] Enter server's IP (Default: 192.168.1.254/24): " server_ip
	read -p "> [+] How many clients would you like to add? " client_count

	cat <<-EOF > ${server_config_file}
		[Interface]
		PrivateKey = ${wg_server_privkey}
		Address = ${server_ip:="192.168.1.254/24"}
		ListenPort = ${random_port}
	EOF
}

clear
print_server_config
print_client_config
