#!/bin/bash
# info: list system interfaces
# options: [FORMAT]
#
# example: v-list-sys-interfaces
#
# This function for obtaining the list of network interfaces.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Argument definition
format="${1-shell}"

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

# JSON list function
json_list() {
	objects=$(echo "$physical_nics" | wc -l)
	i=1
	echo '['
	for interface in $physical_nics; do
		echo -n '    "'$interface'"'
		if [ "$i" -lt "$objects" ]; then
			echo ','
		else
			echo
		fi
		((i++))
	done
	echo ']'
}

# SHELL list function
shell_list() {
	echo "INTERFACE"
	echo "---------"
	for interface in $physical_nics; do
		echo "$interface"
	done
}

# PLAIN list function
plain_list() {
	for interface in $physical_nics; do
		echo "$interface"
	done
}

# CSV list function
csv_list() {
	echo "INTERFACE"
	for interface in $physical_nics; do
		echo "$interface"
	done
}

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Defining interface list
# Detect "physical" NICs only (virtual NICs created by Docker, WireGuard etc. are excluded)
physical_nics="$(ip -d -j link show | jq -r '.[] | if .link_type == "loopback" // .linkinfo.info_kind then empty else .ifname end')"
if [ -z "$physical_nics" ]; then
	physical_nics="$(ip -d -j link show | jq -r '.[] | if .link_type == "loopback" then empty else .ifname end')"
fi

# Listing data
case $format in
	json) json_list ;;
	plain) plain_list ;;
	csv) csv_list ;;
	shell) shell_list ;;
esac

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

exit