#!/bin/bash

# Update Apt cache
sudo apt-get update
# Update Packete
sudo apt-get upgrade -y
# Installiere Wireguard
sudo apt-get install wireguard-tools -y
clear

wireguard_off="#!/bin/bash
sudo wg-quick down wg0
sudo systemctl stop wg-quick@wg0.service"

wireguard_on="#!/bin/bash
sudo wg-quick up wg0
sudo systemctl start wg-quick@wg0.service"

wireguard_icon="https://static-00.iconduck.com/assets.00/wireguard-icon-256x256-bdlmygje.png"

wireguard_app_start="[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
Terminal=true
Exec=/bin/bash /media/wireguard/wireguard_an.sh
Name=Wireguard AN
Icon=/media/wireguard/wireguard.png"

wireguard_app_stop="[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
Terminal=true
Exec=/bin/bash /media/wireguard/wireguard_aus.sh
Name=Wireguard AUS
Icon=/media/wireguard/wireguard.png"

echo "Gebe hier nun die Wireguard Konfiguration ein: (Beende eingabe mit strg+d)"
# Lese die Config Zeile bei Zeile
config=""
while read -r line; do
	config+="$line"$'\n'
done
# Überprüfe ob im etc Ordner ein Wireguard Ordner exestiert, wenn nicht, erstelle diesen
if ! [ -d /etc/wireguard ]; then
	sudo mkdir /etc/wireguard
fi

echo "$config" | sudo tee /etc/wireguard/wg0.conf >/dev/null

sudo systemctl enable wg-quick@wg0.service
sudo systemctl daemon-reload
sudo systemctl start wg-quick@wg0

if ! [ -d /media/wireguard ]; then
	sudo mkdir /media/wireguard
	sudo chown nobody:nogroup /media/wireguard
	sudo chmod a+w /media/wireguard
fi

wget "$wireguard_icon" -O /media/wireguard/wireguard.png

userlist=$(getent passwd | awk -F: '$3>=1000 && $1!="nobody" && $1!="pxadmin" {print $1}')

for user in $userlist; do
	# Allow wg-quick usage
	if sudo grep -q "$user ALL = (ALL) NOPASSWD:/usr/bin/wg-quick" /etc/sudoers; then
		echo "$user darf bereits wg-quick ausführen"
	else
		sudo echo "$user ALL = (ALL) NOPASSWD:/usr/bin/wg-quick" | sudo tee -a /etc/sudoers
	fi
	# Allow stopping wg service
	if sudo grep -q "$user ALL = (ALL) NOPASSWD:/bin/systemctl stop wg-quick@wg0.service" /etc/sudoers; then
		echo "$user darf bereits wg-quick ausführen"
	else
		sudo echo "$user ALL = (ALL) NOPASSWD:/bin/systemctl stop wg-quick@wg0.service" | sudo tee -a /etc/sudoers
	fi
	# Allow starting wg service
	if sudo grep -q "$user ALL = (ALL) NOPASSWD:/bin/systemctl start wg-quick@wg0.service" /etc/sudoers; then
		echo "$user darf bereits wg-quick ausführen"
	else
		sudo echo "$user ALL = (ALL) NOPASSWD:/bin/systemctl start wg-quick@wg0.service" | sudo tee -a /etc/sudoers
	fi
	echo "$wireguard_app_start" >~/.local/share/applications/wireguard_an.desktop
	echo "$wireguard_app_stop" >~/.local/share/applications/wireguard_aus.desktop
done

echo "$wireguard_on" >/media/wireguard/wireguard_an.sh
echo "$wireguard_off" >/media/wireguard/wireguard_aus.sh

if ping -c2 10.200.100.1 >/dev/null; then
	echo "Wireguard wurde erfolgreich eingerichtet"
else
	echo "Wireguard nicht Funktional! 10.200.100.1 konnte nicht angepingt werden!"
fi
