#!/bin/bash

# 
# **** CONSULT WITH NYQUIST SERVER DEVELOPER IF YOU CHANGE ANYTHING IN THIS SCRIPT *****
#
# This script can be used to set the appliance network configuration to either static or 
# DHCP. If using a static address, the user must also provide:
#   1) static IP address
#   2) gateway IP address
#   3) netmask
#	
# 
# Usage
# 
# For static IP address:
#   network_set <caller> static <static ip address> <gateway> <netmask> [<vlanid> <priority>]
#
# For DHCP
#   network_set <caller> dhcp [<vlanid> <priority>]
#

caller=$1
type=$2
paramnum="$#"

INTERFACE_FILE=/etc/network/interfaces
APP_LOC=/opt/bogen/
PRODUCT_NAME=appliance
NETCONFIG=network.config
CONFIG_DIR=/etc/nyquist
SF=SIP.config

NC_FILE=$APP_LOC/$PRODUCT_NAME/$NETCONFIG

previous_type=`sed -n -e "s/^\s*iface.*\(dhcp\|static\)/\1/p" $INTERFACE_FILE`
vlan_iface=`sed -n -e "s/^\s*auto\s*\(eth0\.[:digit:]*\)/\1/p" $INTERFACE_FILE`

# Verify that we are not running in multiple stacked up scripts
tmp_ifs="$IFS"
IFS=$'\n'

ps_list=(`ps -C network_set -o pid --no-header`)
num_copies=${#ps_list[*]}
while [ $num_copies -gt 1 -a ${ps_list[0]:-0} -ne $$ ]; do
	ps_list=(`ps -C network_set -o pid --no-header`)
	num_copies=${#ps_list[*]}
done

IFS="$tmp_ifs"

check_num_parameters()
{
        # Exit if number of parameters are incorrect
        expectedparamnum=$1
        if [ "$paramnum" -gt $expectedparamnum -o "$paramnum" -lt "$((expectedparamnum - 2))" ]; then
                echo "Expected $expectedparamnum arguments - exiting"
                exit 1
        fi
}

repopulate_interfaces()
{
	# Find out if we have VLAN information set in from the asterisk server
	while read cmd_line; do
		declare -g $cmd_line
	done <<- END
		`sed -e "/\(^#\|^$\)/d" -e "s/\s*//g" $CONFIG_DIR/$SF`
	END

	# server VLAN id, if present overrides all
	if [ "${VLAN_ID-unset}" == "unset" ]; then
		# Find out if we have VLAN information set via webui
		while read cmd_line; do
			declare -g $cmd_line
		done <<- END
			`sed -e "/\(^#\|^$\)/d" -e "s/\s*:\s*/=/g" -e "s/\(\w\)\s\+\(\w\)/\1_\2/g" $NC_FILE`
		END

		# If VLAN information is unset in the webui config set it to the parameter
		: ${VLAN_ID=$1}
		: ${PRIORITY_802_1P=$2}
		if [ "$caller" == "webui" ]; then
			VLAN_ID=$1
			PRIORITY_802_1P=${2:-0}
			sudo sed -i "/.*PRIORITY.*$/d;/.*VLAN.*$/d" $NC_FILE
			# Store the VLAN & PRIORITY information
			[ -n "$VLAN_ID" ] && sudo sed -i "1i\VLAN ID: ${VLAN_ID}\nPRIORITY 802 1P: ${PRIORITY_802_1P}" $NC_FILE
		fi
	fi

	# Cleanup old DHCLIENT processes & VLAN interfaces
	if [ "$previous_type" != "$type" -a "$type" != "default" -o  "$vlan_iface" != "${VLAN_ID:+eth0.$VLAN_ID}" ]; then
		network_restart=1
		systemctl stop networking
	fi

	if [ "$VLAN_ID" == "" ]; then
		iface_init="iface eth0 inet"
	else
		iface_init="iface eth0 inet manual\nauto eth0.$VLAN_ID\niface eth0.$VLAN_ID inet"
	fi

	# set the correct timezone if needed
	if [ -n "$TIMEZONE" ]
	then
		TIMEZONE_INFO="$(timedatectl list-timezones)"
		if [ -z "${TIMEZONE_INFO/*$TIMEZONE*/}" ]
		then
			TIMEZONE_INFO="$(timedatectl status)"
			if [ -n "${TIMEZONE_INFO/*Time zone*$TIMEZONE*/}" ]
			then
				echo $TIMEZONE > /etc/timezone
				dpkg-reconfigure --frontend nonintractive tzdata &> /dev/null
			fi
		fi
	fi
	return ${network_restart:-0}
}

if [ "$type" == "default" ]; then
	check_num_parameters 4
	if [ $caller == "rollback" ]; then
		repopulate_interfaces ${3}
	else
		repopulate_interfaces ${vlan_iface/eth0\./}
	fi
	network_restart=$?
	sudo sed -i -e "/\(^\s*iface.*manual\|auto eth0\.\)/d;s/^\s*iface.*\(static\|dhcp\).*/${iface_init} \1/" $INTERFACE_FILE
	if [ $network_restart -eq 1 ]; then
		systemctl --no-block start networking
		disown -a 2>&1 | logger -t "$0"
	elif [ -n "${VLAN_ID:+${PRIORITY_802_1P}}" ]; then
		sudo ip link set eth0.${VLAN_ID} type vlan egress 0:${PRIORITY_802_1P:-0} &> /dev/null
	fi
elif [ "$type" == "dhcp" ]; then
	check_num_parameters 4
	repopulate_interfaces $3 $4
	network_restart=$?

	stdbuf -o0 echo -e "# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
${iface_init} dhcp
# Example to keep MAC address between reboots
" > $INTERFACE_FILE

	#Restart Network
	if [ $network_restart -eq 1 ]; then
		systemctl --no-block start networking
		disown -a 2>&1 | logger -t "$0"
	elif [ -n "$VLAN_ID" ]; then
		sudo ip link set eth0.${VLAN_ID} type vlan egress 0:${PRIORITY_802_1P:-0} &> /dev/null
	fi

elif [ "$type" == "static" ]; then
	check_num_parameters 7
	repopulate_interfaces $6 $7

	stdbuf -o0 echo -e "# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
${iface_init} static
address "$3"
gateway "$4"
netmask "$5"
up systemd-run --no-block --service-type=idle /usr/local/bin/update_configuration ifup || true
" > $INTERFACE_FILE

	#Remove any addresses to guard against having multiple IP addresses assigned
	ip addr flush dev eth0	
	#Restart Network
	systemctl reload-or-restart networking
	[ -n "$VLAN_ID" ] && sudo ip link set eth0.${VLAN_ID} type vlan egress 0:${PRIORITY_802_1P:-0} &> /dev/null
elif [ "$type" == "tftp" ]; then
	check_num_parameters 3
	if [ "$3" == "Option66" ]; then
		# We are using DHCP option 66 to get TFTP Server Address
		echo "Using Option 66"
		sudo sed -i '/TFTP Server:/c\TFTP Server: ' $NC_FILE
		sudo sed -i '/TFTP Source:/c\TFTP Source: Option 66' $NC_FILE
	else
		# An IP address has been provided by the user and will be added
		# to the network.config file
		echo "Using static TFTP Server at $3"
		sudo sed -i "/TFTP Server:/c\TFTP Server: $3" $NC_FILE
		sudo sed -i '/TFTP Source:/c\TFTP Source: Static' $NC_FILE
	fi
else
	echo "Usage: network_set [caller:webui|dhclient|server|rollback] [dhcp|static|tftp] [options]"
fi

cp $INTERFACE_FILE /etc/nyquist/backup/
