#!/bin/bash

# Copyright (C) 2024 Pädagogisches Landesinstitut Rheinland-Pfalz
# Copyright (C) 2024 Daniel Teichmann <daniel.teichmann@das-netzwerkteam.de>
# Moved from mns+-router-config package in 2024

# This script 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 script 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.

cd /var/log || exit 1

TMP="/tmp/logfileview.$$.tmp"

bailout(){
	rm -f "$TMP"
	exit $1
}

if [ -r /etc/sysconfig/i18n ]; then
	. /etc/sysconfig/i18n
elif [ -r /etc/default/locale ]; then
	. /etc/default/locale
fi

export LANG LANGUAGE LC_MESSAGES

while true; do

	LOG=()
	MENU=()
	SIZE=()
	count=0

	#! Priorize D-E-R logfiles! !#
	# But exlude logrotate files (-not -name "*.[0-9]" -not -name "*.gz") ==> .1   .2   .3.gz
	for logfile in `find ./debian-edu-router/ -type f -not -name "*.[0-9]" -not -name "*.gz" 2>/dev/null`; do
		[ -r "$logfile" ] || continue
		LOG[$count]="${logfile#./}"
		SIZE[$count]="$(du -sk "$logfile" | awk '{print $1}')"
		let count++
	done

	# Show the rest of the logfiles too
	# But exlude logrotate files (-not -name "*.[0-9]" -not -name "*.gz") ==> .1   .2   .3.gz
	for logfile in `find . -not -path "*debian-edu-router*" -type f -not -name "*.[0-9]" -not -name "*.gz" 2>/dev/null`; do
		[ -r "$logfile" ] || continue
		LOG[$count]="${logfile#./}"
		SIZE[$count]="$(du -sk "$logfile" | awk '{print $1}')"
		let count++
	done

	for ((i=0; i<count; i++)); do
		MENU[$((i*2))]="$i"
		MENU[$((i*2+1))]="$(printf "%-40.40s %10dkB" "${LOG[$i]}" "${SIZE[$i]}")"
	done

	case "$LANG" in
		de*)
			PLEASE_SELECT="Bitte Logdatei auswählen, Escape zum Beenden."
			;;
		*)
			PLEASE_SELECT="Please select logfile, quit with escape."
			;;
	esac

	# Test if `dialog` is installed #
	if ! /usr/bin/dialog --version &> /dev/null; then
		echo "Error: Failed to execute /usr/bin/dialog! Install it using 'sudo apt install dialog'."
		bailout 1
	fi

	dialog --title "Logfiles" --menu "$PLEASE_SELECT" 25 95 12 "${MENU[@]}" 2>"$TMP" || bailout 0

	read index <"$TMP"
	rm -f "$TMP"
	[ -r "${LOG[$index]}" ] || continue
	SHELL=/bin/false EDITOR=/bin/false mcview -u "${LOG[$index]}"

done
