#!/bin/bash

. ${TOOLKIT}-functions.sh

routelist="$RUNDIR/routelist.tmp"

# (FUNCTIONS)

make_routes()
{
	local eth=$1
	local file="ku-static-routes-$eth"
	local tmp="$file.tmp"

	echo "#!/bin/bash"			>$tmp
	echo "#"				>>$tmp
	echo "# ::copy::"			>>$tmp
	echo "# ::maintainer::"			>>$tmp
	echo "#"				>>$tmp
	echo "[ \$IFACE != $eth ] && exit 0"	>>$tmp

	while read route
	do
		# if doesn't have gateway, direct route to interface
		echo -- "$route" | grep -q " gw " || route="$route $eth"

		# default is to add route, unless "del" is provided
		case "$route" in
		  "")	;;
		  del*)	echo "route $route"	>>$tmp ;;
		  add*)	echo "route $route"	>>$tmp ;;
		  *)	echo "route add $route"	>>$tmp ;;
		esac
		echo "  $eth: routing $route"
	done
	echo "exit 0"				>>$tmp

	installfile $tmp /etc/network/if-up.d/$file root:root 775
	rm -f $tmp
	echo "$file" >>$routelist
	return 0
}

# update autogenerated block in /etc/hosts template file
#
create_hosts_file()
{
	local if_schema="$1"
	local skip="false"
	local line=
	local ip=

	fgrep -q "DO NOT MODIFY, WILL BE OVERWRITTEN ON NEXT UPDATE" /etc/hosts && {
		putwarning "/etc/hosts" \
			"file /etc/hosts seems to be automatically created by" \
			"kusa, removing it; original file saved in /etc/hosts.save" >&2
		mv /etc/hosts /etc/hosts.save
		cp /dev/null /etc/hosts
	}
	
	# remove kusa block
	#
	cat /etc/hosts | while read ip line
	do
	    case $line in
		"DO NOT EDIT BLOCK BELOW"*)	skip=true ;;
		"END OF AUTOGENERATED"*)	skip=false ;;
		*) $skip || echo "$ip	$line" ;;
	    esac
	done

	# recreate kusa block
	#
	echo "# DO NOT EDIT BLOCK BELOW -- kusa AUTOGENERATED"
	echo
	echo "127.0.0.1	localhost"
	echo
	echo "# The following lines are desirable for IPv6 capable hosts"
	echo "::1     localhost ip6-localhost ip6-loopback"
	echo "fe00::0 ip6-localnet"
	echo "ff00::0 ip6-mcastprefix"
	echo "ff02::1 ip6-allnodes"
	echo "ff02::2 ip6-allrouters"
	echo "ff02::3 ip6-allhosts"
	echo

	case $if_schema in
  	  dhcp|none)	ip="127.0.0.1" ;;
  	  *) 		ip="::network.network::.::network.address::" ;;
	esac

	echo "$ip	::network.hostname::.::network.domain:: ::network.hostname::"
	echo
	echo "# END OF AUTOGENERATED BLOCK -- kusa"

	return 0
}



# (MAIN)

if_schema=$(jtconf network.if_schema 2>/dev/null) || :
s_origin="network.if_schema"

[ "X$if_schema" = "X" ] && {
	[ "$(jtconf network.address 2>/dev/null)" = "dhcp" ] && {
		if_schema="dhcp"
		s_origin="network.address"
	}
}
[ "X$if_schema" = "X" ] && {
	[ "$(jtconf network.address 2>/dev/null)" = "none" ] && {
		if_schema="none"
		s_origin="network.address"
	}
}
[ "X$if_schema" = "X" ] && {
	if_schema="base"	# default
	s_origin="(default)"
}

# decido se mi serve network-manager se questa macchina
# non ha installato un kernel server e se usa dhcp (quindi
# probabilmente e` un laptop o un desktop con ip dinamico)
# oppure 'none' 
#
if jtconf network.network_manager 2>/dev/null >/dev/null # override by config
then
	if getconfirm network.network_manager
	then
		netmanager=true
	else
		netmanager=false
	fi
else
	netmanager=false

	# forced by class?
	#
	case $if_schema in
   	    dhcp|none|laptop*)
		class_requested "ws"		&& netmanager=true
		class_requested "laptop"	&& netmanager=true
		;;
	esac

	# last check, restrained by architecture?
	#
	service_requested "arch-alix"	&& netmanager=false
	service_requested "arch-xen"	&& netmanager=false
fi



# build static routes if-up.d scripts
#
:> $routelist

for int in $(jtconf --list "network_")
do
	int=${int/network_/}

	routes=$(jtconf network_$int.routes 2>/dev/null || :)
	[ "X$routes" = "X" ] && continue
	echo "$routes" | make_routes $int
done

# check for old, deprecated formats
#
oldformat=$(jtconf --listvars network | grep 'routes-' || :)
[ "X$oldformat" != "X" ] && {
	putwarning "INVALID net, routes" \
		"those network.routes and network.routes-<int> definitions" \
		"are now invalid, you must convert them to new format network_<int>.routes"
	echo -e "\n$oldformat\n"
	exit 1
}

# cleanup
for file in $( (cd /etc/network/if-up.d; ls ku-static-routes-* 2>/dev/null) )
do
	grep -q "^$file$" $routelist || {
		echo "  purging obsolete routefile $file"
		rm -f /etc/network/if-up.d/$file
	}
done



# check for aliases (secondary addresses, multihomed machines)
#
export tmp_net_aliases=		# env temp used in templates
ifup_cmds=

for int in $(jtconf --list "network_")
do
	int=${int/network_/}

	for netalias in $(jtconf --listvars "network_$int" | grep "^[1-9]_address")
	do
		netalias=${netalias/_address/}

		key="network_$int.$netalias"
		addr=$(jtconf ${key}_address)
		desc=$(jtconf ${key}_desc 2>/dev/null)	|| desc="(from ${key}_adddress)"
		mask=$(jtconf ${key}_mask 2>/dev/null)	|| mask="255.255.255.0"
		gw=$(jtconf ${key}_gateway 2>/dev/null)	&& gw=" gateway $gw"

		echo "  adding alias: $int:$netalias $addr - $desc"

		tmp_net_aliases="$tmp_net_aliases
# $int:$netalias - $desc
#
auto $int:$netalias
	iface $int:$netalias inet static
	address $addr
	netmask $mask
$gw"
		ifup_cmds="$ifup_cmds ifup $int:$netalias ;"
	done
done

echo "  interfaces schema: $if_schema - defined by: $s_origin"
installfile interfaces.$if_schema /etc/network/interfaces root:root 644

if $netmanager
then
	echo " needs NetworkManager"
	install_pkgs network-manager network-manager-gnome #network-manager-kde
else
	remove_pkgs network-manager network-manager-gnome network-manager-kde
fi

dns_server=$(jtconf service.dns)
my_ip=$(jtconf network.network).$(jtconf network.address)
kusa_controls_resolvconf=true

create_hosts_file $if_schema >hosts.tmp

if [ "X$dns_server" = "X$my_ip" -a ! -L /etc/dns ]
then
	putwarning "DNS SERVER" \
		"I'm my own dns server, but the service is not yet configured" \
		"(/etc/dns symlink to /etc/dnslocal directory not found), so" \
		"I will not touch /etc/resolv.conf at the moment"
	rm -f /etc/kusa/resolv.conf
else
	fallback_dns=$(jtconf service.fallback_dns 2>/dev/null) || :
	export tmp_fallback_dns=
	[ "X$fallback_dns" != "X" ] && {
		for srv in $fallback_dns
		do
			echo "  resolv.conf: adding fallback nameserver $srv"
			tmp_fallback_dns=$(echo -e "$tmp_fallback_dns\nnameserver $srv")
		done
	}

	# depending if dhcp is used or not, we install resolv.conf in the
	# final destination; if dhcp is on we don't want to disrupt the
	# actual file during configuration task, it will be overwritten by
	# kuwatcher later
	#
	case $if_schema in
	  none)
	  	;;
  	  *dhcp*|laptop*)
		getconfirm network.dhcp_resolv && kusa_controls_resolvconf=false
	  	;;
  	  *)	installfile resolv.conf /etc/		root:root 644
		;;
	esac

	file="/etc/kuwatcher/conf.d/auto-resolv-conf"

	if $kusa_controls_resolvconf
	then
		# resolv.conf is always copied in /etc/kusa directory, as reference
		# for any change made by other programs (like dhcp client)
		#
		installfile resolv.conf			/etc/kusa/	root:root 444
		installfile kuwatcher-auto-resolv-conf	$file		root:root 444
	else
		uninstallfiles $file
		purgefiles $file
	fi
fi

installfile hosts.tmp /etc/hosts	root:root 644



file="/etc/ku-resolv-blacklist"
[ -f "$file" ] || {
	installfile ku-resolv-blacklist $file root:root 664
}


# IPV6?
#
file_enable="75-ku-enable-ipv6.conf"
file_disable="75-ku-disable-ipv6.conf"
dir="/etc/sysctl.d"

if getconfirm network.enable_ipv6
then
	installfile $file_enable $dir/ root:root 444
	uninstallfiles $dir/$file_disable
else
	installfile $file_disable $dir/ root:root 444
	uninstallfiles $dir/$file_enable
fi


# 2022-04-01
# patch 00check-network-cable (from ifupdown-extra) if needed
#
file="/etc/network/if-up.d/00check-network-cable"
[ -f $file ] && {
	head -1 $file | grep -q "#!/bin/sh" && {
		echo "  * replacing broken $file ..."
		installfile "00check-network-cable" "$file" root:root 444
	}
}


$SOMETHING_CHANGED && {
	restart_service kuwatcher

	in_chroot || {

		# in case we have changed sysctl files ...
		#
		ls /etc/sysctl.d/*.conf | xargs -n 1 /sbin/sysctl -p

		echo "  setting hostname: $(cat /etc/hostname)"
		hostname -F /etc/hostname

		# pericoloso, esegue restart del network solo se richiesto
		# esplicitamente attraverso il service 'restart_network'
		# (opzione -s)
		#
		service_requested restart_network && {
			invoke-rc.d networking restart
		}
	}
}

exit 0
