#!/bin/sh

. /lib/functions.sh
PACKAGE_FILE="/etc/package_restore.txt"

[ -s "$PACKAGE_FILE" ] && {
	sed -i "s/tlt_custom_pkg_//g" "$PACKAGE_FILE"
	sed -i "/wireguard/d" "$PACKAGE_FILE"
	sed -i "/coStreamApp - Cloud of Things/s/.*/cmStreamApp - Cumulocity - Cloud of Things/" "$PACKAGE_FILE"
	sed -i "/cmStreamApp - Cumulocity/s/.*/cmStreamApp - Cumulocity - Cloud of Things/" "$PACKAGE_FILE"
	sed -i "s/pamd/pam/g" "$PACKAGE_FILE"
}

get_interface() {
	local enabled proto

	config_get enabled "$1" "$2" ""
	config_get proto "$1" "proto" ""

	[ "$enabled" = "$4" ] && [ "$proto" = "$3" ] && ENABLED="1"
}

get_enabled() {
	local enabled

	config_get_bool enabled "$1" "$2" "0"

	[ "$enabled" -eq 1 ] && ENABLED="1"
}

check_config() {
	local config="$1"
	local section="$2"
	local enabled_option="$3"
	local pkg_name="$4"
	local full_name="$5"
	local check=0

	ENABLED="0"
	config_load "$config"

	case "$config" in
	"network")
		config_foreach get_interface "$section" "$enabled_option" "$6" "$7"
		;;
	*)
		config_foreach get_enabled "$section" "$enabled_option"
		;;
	esac

	[ -f "$PACKAGE_FILE" ] && check=$(grep -c -w "$pkg_name" "$PACKAGE_FILE" 2>/dev/null)
	[ "$ENABLED" -eq 1 ] && [ "$check" -eq 0 ] && echo "$pkg_name - $full_name" >> "$PACKAGE_FILE"
}

check_config "hostblock" "hostblock" "enabled" "web_filter" "WEB Filter"
check_config "privoxy" "privoxy" "enabled" "web_filter" "WEB Filter"
check_config "system" "system" "tcp_dump" "tcpdump" "TCPdump"
check_config "network" "interface" "disabled" "sstp-client" "SSTP" "sstp" "0"
check_config "frr" "bgp_general" "enabled" "frr-bgpd" "BGP daemon"
check_config "frr" "rip_general" "enabled" "frr-ripd" "RIP daemon"
check_config "frr" "ospf" "enabled" "frr-ospfd" "OSPFv2 daemon"
check_config "frr" "nhrp_general" "enabled" "frr-nhrp" "NHRP daemon"
check_config "frr" "eigrp_general" "enabled" "frr-eigrpd" "EIGRP daemon"
check_config "modbus_serial_master" "rs232" "enabled" "modbus_serial_master" "Modbus Serial Master"
check_config "modbus_serial_master" "rs485" "enabled" "modbus_serial_master" "Modbus Serial Master"

exit 0
