#!/bin/bash -login

# Copyright (C) 2010-2023 Pädagogisches Landesinstitut Rheinland-Pfalz
# Copyright (C) 2022-2023 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
# Copyright (C) 2022-2023 Daniel Teichmann <daniel.teichmann@das-netzwerkteam.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

export PATH="/bin:/sbin:/usr/bin:/usr/sbin"

export TEXTDOMAIN="debian-edu-router-config"

if [ -e /etc/debian-edu/router.conf ]; then
	source /etc/debian-edu/router.conf
fi
PRODUCTNAME="${PRODUCTNAME:-"Debian Edu Router"}"

# source gettext tools
. gettext.sh

# for system info
. /etc/os-release

WELCOME_HEADER=`printf "$(eval_gettext "Welcome to %s %s (%s) on %s")" "${NAME}" "${VERSION}" "$(uname -m)" "${HOSTNAME}"`
NETWORK_DOWN="$(eval_gettext "WARNING: All networks are currently down. Check your configuration.")"
MACHINE_ID=$(eval_gettext "machine ID")

MENU_HEADER=`printf "$(eval_gettext "%s Menu")" "${PRODUCTNAME}"`
ITEM_SETUP=`printf "$(eval_gettext "%s Configuration")" "${PRODUCTNAME}"`
ITEM_SHELL=$(eval_gettext "Launch a shell session")
ITEM_IPTRAF=$(eval_gettext "IP traffic statistics")
ITEM_REBOOT="$(eval_gettext "Reboot system")"
ITEM_SHUTDOWN="$(eval_gettext "Shutdown system")"
ITEM_QUIT=`printf "$(eval_gettext "Quit menu and logout as user '%s'")" "${USER}"`
SELECT_MSG=$(eval_gettext "Please select: ")

CMD_CHOSEN_IPTRAF=$(eval_gettext "Starting IPTRAF traffic monitor...")
CMD_CHOSEN_SHELL=`printf "$(eval_gettext "Starting shell '%s'...")" "${SHELL}"`
CMD_CHOSEN_SETUP=`printf "$(eval_gettext "Entering %s configuration submenu...")" "${PRODUCTNAME}"`
CMD_CHOSEN_QUIT=$(eval_gettext "Quit")

SUBMENU_SETUP_HEADER=`printf "$(eval_gettext "%s Configuration")" "${PRODUCTNAME}"`
ITEM_DER_NETWORK_SETUP=`printf "$(eval_gettext "Configure %s network settings")" "${PRODUCTNAME}"`
ITEM_DER_FIREWALL_SETUP=`printf "$(eval_gettext "Configure %s firewall settings")" "${PRODUCTNAME}"`
ITEM_DER_SERVICES_SETUP=`printf "$(eval_gettext "Configure %s services")" "${PRODUCTNAME}"`

CMD_CHOSEN_NETWORKSETUP=$(eval_gettext "Configure networking...")
CMD_CHOSEN_FIREWALLSETUP=$(eval_gettext "Configure firewall settings...")
CMD_CHOSEN_SERVICESSETUP=$(eval_gettext "Configure services...")
CMD_CHOSEN_BACK=$(eval_gettext "Back to main menu")

ITEM_QUIT_SUBMENU=$(eval_gettext "Return back to main menu")

# Reboot stuff
ITEM_REBOOT_SELECT_MSG=$(eval_gettext "Are you sure you want to reboot the system? Type in 'imsure':")
ITEM_REBOOT_DISCLAIMER=$(eval_gettext "WARNING!
Make sure you still have (physical) access to the machine in case the boot
process fails. If this is a VM Guest, make sure you have access to the
VM Host. An internet downage can easily ruin your day!
You have been warned.")
ITEM_REBOOT_VALID_INPUT=$(eval_gettext "imsure")
ITEM_REBOOT_SLEEP_TIME="5"
ITEM_REBOOT_REBOOTING_NOW=`printf "$(eval_gettext "OK. Rebooting %s in %s seconds!")" "${PRODUCTNAME}" "${ITEM_SHUTDOWN_SLEEP_TIME}"`

# Shutdown stuff
ITEM_SHUTDOWN_SELECT_MSG=$(eval_gettext "Are you sure you want to shut down the system? Type in 'imsure':")
ITEM_SHUTDOWN_DISCLAIMER=$(eval_gettext "WARNING!
Make sure you still have (physical) access to the machine!
If this is a VM Guest, make sure you have access to the
VM Host. An internet downage can easily ruin your day!
You have been warned.")
ITEM_SHUTDOWN_VALID_INPUT=$(eval_gettext "imsure")
ITEM_SHUTDOWN_SLEEP_TIME="5"
ITEM_SHUTDOWN_SHUTTING_DOWN_NOW=`printf "$(eval_gettext "OK. Shutting down %s in %s seconds!")" "${PRODUCTNAME}" "${ITEM_SHUTDOWN_SLEEP_TIME}"`

underline() { echo $1; echo "${1//?/${2:-=}}";}

fill_with_trailing_blanks() {
	length=$1
	string=$2
	printf "%-${length}s" "${string}"
}

header() {
	echo -e "\033[1m*** ${WELCOME_HEADER} ***\033[0m"
	echo

	echo -n "${PRODUCTNAME}"
	if [ -e /etc/machine-id ]; then
		echo ", ${MACHINE_ID}: $(cat /etc/machine-id)"
	else
		echo
	fi
	echo

	ip_addresses_shown=false

	cd /etc/network/interfaces.d/
	configs="$(find . -name '*d-e-r*' | sort | grep -v VLAN)"
	if [ -n "${configs}" ]; then
		for ifaceconf in ${configs}; do
			if [ -e "${ifaceconf}" ]; then
				iface=`cat "${ifaceconf}" | grep -E "^iface .*" | cut -d " " -f2`
				if [ -n "$iface" ]; then
					network=`echo "${ifaceconf}" | cut -d"_" -f3`
					addr_v4=`ip a show ${iface} 2>/dev/null | grep "inet " | awk '{print $2}' | head -n1`
					macaddress=`ip addr show ${iface} | grep "link/ether" | grep -o -E ..:..:..:..:..:.. | head -1`
					if [ -n "${addr_v4}" ]; then
						echo "`fill_with_trailing_blanks 24 ${network}`-> `fill_with_trailing_blanks 10 $iface` -> v4: `fill_with_trailing_blanks 18 ${addr_v4}` [${macaddress}]"
						ip_addresses_shown=true
					fi
				fi
			fi
		done
		if [ ${ip_addresses_shown} = false ]; then
			echo -e "\033[1m${NETWORK_DOWN}\033[0m"
		fi
		echo
	fi
	echo
	cd - 1>/dev/null
}

submenu_reboot() {
	local t

	echo -e "${ITEM_REBOOT_DISCLAIMER}"
	read -p "
[1m${ITEM_REBOOT_SELECT_MSG}[0m " t
	case "$t" in
		${ITEM_REBOOT_VALID_INPUT}) echo -e "\033[1m${ITEM_REBOOT_REBOOTING_NOW}\033[0m"; sleep "$ITEM_REBOOT_SLEEP_TIME"; reboot now;;
		*) echo -e "\033[1m${CMD_CHOSEN_BACK}\033[0m"; echo;;
	esac
	echo

	sleep 1
}

submenu_shutdown() {
	local t

	echo -e "${ITEM_SHUTDOWN_DISCLAIMER}"
	read -p "
[1m${ITEM_SHUTDOWN_SELECT_MSG}[0m " t
	case "$t" in
		${ITEM_SHUTDOWN_VALID_INPUT}) echo -e "\033[1m${ITEM_SHUTDOWN_SHUTTING_DOWN_NOW}\033[0m"; sleep "$ITEM_SHUTDOWN_SLEEP_TIME"; shutdown now;;
		*) echo -e "\033[1m${CMD_CHOSEN_BACK}\033[0m"; echo;;
	esac
	echo

	sleep 1
}

submenu_setup(){
	local t
	while true; do
		echo -e "\033[1m$(underline "${SUBMENU_SETUP_HEADER}" "-")\n\n" \
				"\t n - ${ITEM_DER_NETWORK_SETUP}\n"                    \
				"\t f - ${ITEM_DER_FIREWALL_SETUP}\n"                   \
				"\t s - ${ITEM_DER_SERVICES_SETUP}\n"                   \
				"\t m - ${ITEM_QUIT_SUBMENU}\n"                         \
				"\033[0m"
		read -p "
[1m${SELECT_MSG}[0m" -s -n 1 t
		case "$t" in
			[nN]) echo -e "\033[1m${CMD_CHOSEN_NETWORKSETUP}\033[0m"; CONFIGURE_ONLY="NETWORK_ALL" dpkg-reconfigure debian-edu-router-config;;
			[fF]) echo -e "\033[1m${CMD_CHOSEN_FIREWALLSETUP}\033[0m"; CONFIGURE_ONLY="FIREWALL_ALL" dpkg-reconfigure debian-edu-router-config;;
			[sS]) echo -e "\033[1m${CMD_CHOSEN_SERVICESSETUP}\033[0m"; CONFIGURE_ONLY="SERVICES_ALL" dpkg-reconfigure debian-edu-router-config;;
			[mM]) echo -e "\033[1m${CMD_CHOSEN_BACK}\033[0m"; echo; break;;
		esac
		echo
	done
	sleep 1
}

menu(){
	local t
	echo -e "\033[1m$(underline "${MENU_HEADER}")\n\n" \
			"\t i - ${ITEM_IPTRAF}\n"                  \
			"\t s - ${ITEM_SHELL}\n"                   \
			"\t c - ${ITEM_SETUP}\n"                   \
			"\t r - ${ITEM_REBOOT}\n"                  \
			"\t x - ${ITEM_SHUTDOWN}\n"                \
			"\t q - ${ITEM_QUIT}\n"                    \
			"\033[0m"
	while true; do
		read -p "
[1m${SELECT_MSG}[0m" -s -n 1 t
		case "$t" in
			[iI]) echo -e "\033[1m${CMD_CHOSEN_IPTRAF}\033[0m"; echo; iptraf; reset; header; break;;
			[sS]) echo -e "\033[1m${CMD_CHOSEN_SHELL}\033[0m"; echo; bash -login; reset; echo; header; break;;
			[cC]) echo -e "\033[1m${CMD_CHOSEN_SETUP}\033[0m"; echo; submenu_setup; reset; echo; header; break;;
			[rR]) echo -e "\033[1m${CMD_CHOSEN_REBOOT}\033[0m"; echo; submenu_reboot; reset; echo; header; break;;
			[xX]) echo -e "\033[1m${CMD_CHOSEN_SHUTDOWN}\033[0m"; echo; submenu_shutdown; reset; echo; header; break;;
			[qQ]) echo -e "\033[1m${CMD_CHOSEN_QUIT}\033[0m"; echo; exit 0; break;;
		esac
	done
}

echo

if [ `id -u` = 0 ]; then

	header

	# Interactive mode for root
	while true; do menu; done

else
	exec bash -login
fi
