#!/bin/bash
{
	#////////////////////////////////////
	# DietPi
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#////////////////////////////////////
	#
	# Info:
	# - Obtains the optimal MTU size.
	#
	# Usage:
	# - dietpi-optimal_mtu 					| Tests using google.com
	# - dietpi-optimal_mtu URL/IP address	| Tests using the provided URL/IP
	#////////////////////////////////////

	#Grab Input
	URL='www.google.com'
	if [ "$1" != "" ]; then
		URL="$1"
	fi

	#Import DietPi-Globals ---------------------------------------------------------------
	. /DietPi/dietpi/func/dietpi-globals
	export G_PROGRAM_NAME='DietPi-Optimal_mtu'
	#Import DietPi-Globals ---------------------------------------------------------------

	MTU_SIZE=1500
	TEST_MTU_SIZE=0
	SUCCESS=0

	#-----------------------------------------------------------------------------------
	echo -e "DietPi - MTU optimal size tool\n - Finding optimal MTU size, please wait..."
	while (($SUCCESS == 0))
	do
		#remove ipv4 icmp headers from total size
		TEST_MTU_SIZE=$(( $MTU_SIZE - 28 ))

		echo -e "Testing MTU: $MTU_SIZE"
		if (( $(ping -c 1 -s $TEST_MTU_SIZE -M do $URL | grep -ci -m1 '+1 error') == 0 ));then
			SUCCESS=1
			echo -e "\nCompleted:\n - MTU optimal size = $MTU_SIZE\n"
		elif (( $MTU_SIZE <= 0 )); then
			echo -e "\nERROR:\n - Failed to find MTU size\n"
		else
			((MTU_SIZE--))
		fi
	done

	#-----------------------------------------------------------------------------------
	exit
	#-----------------------------------------------------------------------------------
}