#!/bin/sh
REAL_INI_FILES="/etc/ptpd.ini"
DUMMY_INI_FILES="/tmp/.ptpd.ini"
MODULE_FILES="/etc/modprobe.d/aliases"
INI_PARSER="iniparse -f ${DUMMY_INI_FILES}"
PTPD_LOG="/var/log/ptpd.log"
INTERFACES="eth6 eth7 eth8 eth9"
PTPD_OPTIONS="-c"
: ${DIALOG=dialog}

tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
trap "rm -f $tempfile" 0 1 2 5 15


function MainMenu() {
	$DIALOG --clear --item-help --cancel-label "Exit" --title "MOXA DA-683" \
	        --menu "The Precision Time Protocol (PTP) is a high-precision time protocol for synchronization used in measurement and control systems within the local area network. \nMoxa's PTPd is a complete implementation of the Version 2 IEEE 1588 specifications. It has been tested and is known to work properly with other IEEE 1588 implementations, such as IMSYS corp master clock. Choose the configuration options that closely match your environment.  
	\n\n\
Choose the options:" 20 100 4 \
	        "Wizard" "For dummies users to setup PTP protocol in a few steps." "..." \
	        "Basic Settings"  "For user who have common understanding of PTP protocol."    "..." \
	        "Advanced Settings" "For user who are able to use PTP protocol advanced techniques." "..." \
	        "Monitor"  "Protocol monitor and analyzer" "..." \
	        "Apply"  "Apply settings to your system" "..." 2> $tempfile

	choice=`cat $tempfile`;
	case $choice in
		"Basic Settings")
	 		echo "OK 'basic' chosen.";
	 		BasicMenu;;
	 	"Advanced Settings")
	 		echo "OK 'advanced' chosen.";
	 		AdvancedMenu;;
	 	"Wizard")
	 		echo "OK 'wizard' chosen.";
	 		WizardMenu;;
		"Monitor")
	 		echo "Monitor pressed.";
	 		MonitorMenu;;
		"Apply")
	 		echo "Apply pressed.";
	 		ApplyMenu;;
		*)
	 		echo "Clean ui setting... $retval";
	 		clear ;
	 		exit 1;;
	esac

}

function SyncSystemClockMenu() {
no_adj_sysclock=`${INI_PARSER} -s system -n no_adj_sysclock -d 0`
$DIALOG --backtitle "Sync System Clock Selection" \
	--title "Select sync option" --clear \
        --radiolist "Moxa's DA683 PTPd Hardware Clock is designed independently with the System Hardware Clock. Choose 'disable' if you do not prefer to sync the clock; Choose 'enable' will allow PTPd daemon automatically sync PTPd Hardware Clock to System Hardware Clock.\n\n\
Press SPACE to toggle an option on/off." 25 100 5 \
        "enable"  "allow ptpd to adjust your system timer" `if [ "$no_adj_sysclock" == "0" ]; then echo "ON"; else echo "off" ; fi` \
        "disable" "run as independence timer" `if [ "$no_adj_sysclock" == "1" ]; then echo "ON"; else echo "off" ; fi`  2> $tempfile
retval=$?
choice=`cat $tempfile`
case $retval in
  0)
    echo "'$choice' chosen.";
    if [ $choice == "enable" ] ; then
	val=0
    else
	val=1
    fi
    ${INI_PARSER} -s system -n no_adj_sysclock -v $val;;
  1)
    echo "Cancel pressed.";;
  255)
    echo "ESC pressed.";;
esac

BasicMenu
}


function InterfaceMenu() {
ether=`${INI_PARSER} -s system -n interface -d eth6`
$DIALOG --backtitle "Network Interface Selection" \
	--title "Select Interface" --clear \
        --radiolist "Moxa's DA-683 is a PTPd slave, it's ethernet ports fully support PTP version 2 message hardware time stamping. Check the label located at the DA-683 Ethernet where you connect to boundary clock or master clock, and select the appropriate port number that suits your enviroment.\n\n\
Press SPACE to toggle an option on/off." 25 100 5 \
        "eth6"  "IEEE1588 ethernet LAN 6" `if [ "$ether" == "eth6" ]; then echo "ON"; else echo "off" ; fi` \
        "eth7"  "IEEE1588 ethernet LAN 7" `if [ "$ether" == "eth7" ]; then echo "ON"; else echo "off" ; fi` \
        "eth8"  "IEEE1588 ethernet LAN 8" `if [ "$ether" == "eth8" ]; then echo "ON"; else echo "off" ; fi` \
        "eth9"  "IEEE1588 ethernet LAN 9" `if [ "$ether" == "eth9" ]; then echo "ON"; else echo "off" ; fi` 2> $tempfile
retval=$?
choice=`cat $tempfile`
case $retval in
  0)
    echo "'$choice' chosen.";
    ${INI_PARSER} -s system -n interface -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    echo "ESC pressed.";;
esac
BasicMenu
}


function ModeMenu() {
e2e_mode=`${INI_PARSER} -s system -n e2e_mode -d 0`
$DIALOG --backtitle "PTPd Protocol Selection" \
	--title "Select Mode" --clear \
        --radiolist "For the switches and routers that have implemented transparent clocks, either the end-to-end (E2E) method or peer-to-peer (P2P) method must be selected.\n\n\
In addition to provide PTP event transit time information, the peer-to-peer transparent clock (P2P TC) is a transparent clock that also provides corrections for the propagation delay of the link connected to the port receiving the PTP event message. In the presence of peer-to-peer transparent clocks, delay measurements between slave clocks and the master clock are performed using the peer delay measurement mechanism.\n\n\
An end-to-end transparent clock (E2E TC) only measures the time taken for a PTP event message to transit the device and provides this information to clocks receiving this PTP event message.\n\n\
Press SPACE to toggle an option on/off." 25 100 5 \
        "P2P"  "P2P mode." `if [ "$e2e_mode" == "2" ]; then echo "ON"; else echo "off" ; fi` \
        "E2E"    "E2E mode." `if [ "$e2e_mode" == "1" ]; then echo "ON"; else echo "off" ; fi` 2> $tempfile
retval=$?
choice=`cat $tempfile`
case $retval in
  0)
    echo "'$choice' chosen.";
    if [ $choice == "P2P" ] ; then
	val=2
    else
	val=1
    fi
    ${INI_PARSER} -s system -n e2e_mode -v $val;;
  1)
    echo "Cancel pressed.";;
  255)
    echo "ESC pressed.";;
esac

BasicMenu
}

function BasicMenu() {
	$DIALOG --clear --item-help --cancel-label "Exit" --title "Basic Setting" \
	        --menu "Moxa's PTPd provide a very basic setup for customers who have common understanding of PTPd protocol. The following options allow user to set the PTPd network interface and customize protocol used by PTP daemon.\n\
	\n\n\
Choose the options:" 20 80 0 \
	        "Mode"  "Select p2p/e2e mode"    "..." \
	        "Interface" "Select Network interface" "..."\
	        "Sync" "Sync to system clock" "..." 2> $tempfile

	choice=`cat $tempfile`;
	case $choice in
		"Mode")
	 		echo "OK 'basic' chosen.";
	 		ModeMenu;;
		"Interface")
	 		echo "Apply pressed.";
	 		InterfaceMenu;;
	 	"Sync")
	 		echo "OK 'advanced' chosen.";
	 		SyncSystemClockMenu;;
		*)
	 		echo "Unrecognize options";;
	esac

}

function P2PIntervalMenu() {
delay=`${INI_PARSER} -s p2p -n delay -d 0`
$DIALOG --title "P2P Interval Setting" --clear \
        --inputbox "Peer-to-peer (P2P) method uses the peer delay measurement mechanism to determine the delay or latency between slave and TC/Master. Users are advised to set the PDELAY packet request time interval long enough in case the TC/Master is unable to serve large node in the same time. The interval is converted in 2^NUMBER sec.
You can use BACKSPACE to correct errors. \n\n
Interval in 2^NUMBER sec" 20 80 $delay 2> $tempfile

retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ${INI_PARSER} -s p2p -n delay -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function E2EIntervalMenu() {
delay=`${INI_PARSER} -s e2e -n delay -d 0`
$DIALOG --title "E2E Interval Setting" --clear \
        --inputbox "End-to-Eeer (E2E) method use the delay-request measurement mechanism to determine the delay or latency between slave and TC/Master. Users are advise to set the DELAY REQUEST packet request time interval long enought especially in heavy network throughput enviroment. The interval is converted in 2^NUMBER sec.\n
You can use BACKSPACE to correct errors. \n\n
Interval in 2^NUMBER sec" 20 80 $delay 2> $tempfile

retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ${INI_PARSER} -s e2e -n delay -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function MulticastTTLMenu() {
ttl=`${INI_PARSER} -s system -n ttl -d 1`
$DIALOG --title "Multicast TTL Setting" --clear \
        --inputbox "The IP multicast routing protocol uses the Time To Live (TTL) field of IP datagrams to decide how "far" from a sending host a given multicast packet should be forwarded. The default TTL for multicast datagrams is 1, which will result in multicast packets going only to other hosts on the local network.\n
You can use BACKSPACE to correct errors. \n\n
Interval in 1,32,64,128" 20 80 $ttl 2> $tempfile

retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ${INI_PARSER} -s system -n ttl -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function ForeignMasterMenu() {
max_foreign_record=`${INI_PARSER} -s system -n max_foreign_record -d 5`
$DIALOG --title "Foreign Master Setting" --clear \
        --inputbox "A master clock may receive Sync messages from other clocks which is called 'foreign masters'. Users are able to specify PTPd maximal number of foreign master records\n
You can use BACKSPACE to correct errors. \n\n
Number of maximum foreign master records are 255" 20 80 $max_foreign_record 2> $tempfile

retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ${INI_PARSER} -s system -n max_foreign_record -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function UtcOffsetMenu() {
utc_offset=`${INI_PARSER} -s system -n utc_offset -d 0`
$DIALOG --title "UTC Offset Setting" --clear \
        --inputbox "Users are able to tune current system clock with UTC Offset when PTPd synchronizes the master clock timer.\n
You can use BACKSPACE to correct errors. \n\n
UTC Offset" 20 80 $utc_offset 2> $tempfile

retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ${INI_PARSER} -s system -n utc_offset -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function DomainMenu() {
domain=`${INI_PARSER} -s system -n domain -d 0`
$DIALOG --title "PTPd Domain Setting" --clear \
        --inputbox "A master clock may set to different domain number. Users are able to specify PTPd domain number to reach master foreign master records \n
You can use BACKSPACE to correct errors. \n\n
Number of domain" 20 80 $domain 2> $tempfile

retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ${INI_PARSER} -s system -n domain -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function ClockOffsetFilterMenu() {
clock_filter_1s=`${INI_PARSER} -s system -n clock_filter_1s -d 0`
$DIALOG --backtitle "Clock Offset Filter Selection" \
	--title "Select Clock Filter" --clear \
        --radiolist "Do not reset PTPd Hardware Clock if Master Clock timer offset is off by more than 1 seconds. This option is usable especially for slave to filter the faulty reference timer.\n
You can use BACKSPACE to correct errors. \n\n\
Press SPACE to toggle an option on/off." 25 100 5 \
        "enable"  "Do not reset the clock if off by more than one second" `if [ "$clock_filter_1s" == "1" ]; then echo "ON"; else echo "off" ; fi` \
        "disable" "Reset the clock if off by more than one second" `if [ "$clock_filter_1s" == "0" ]; then echo "ON"; else echo "off" ; fi` 2> $tempfile

retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    if [ $choice == "enable" ] ; then
	val=1
    else
	val=0
    fi
    ${INI_PARSER} -s system -n clock_filter_1s -v $val;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function DelayOffsetFilterMenu() {
delay_filter_1s=`${INI_PARSER} -s system -n delay_filter_1s -d 0`
$DIALOG --title "Delay Filter Setting" --clear \
        --inputbox "Do not accept delay value if offset is off by more than nanoseconds. This option is usable especially for slave to filter the faulty reference timer. \n
You can use BACKSPACE to correct errors. \n\n
Number of nanoseconds delay" 20 80 $delay_filter_1s 2> $tempfile

retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ${INI_PARSER} -s system -n delay_filter_1s -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function SelectEnviromentModeMenu() {
adaptive=`${INI_PARSER} -s system -n adaptive -d "High Accuracy Clock"`
$DIALOG --backtitle "Environmental Adaptation Select" \
	--title "Select mode" --clear  --ok-label "Select"\
        --radiolist "Moxa's DA-683 provids a powerful configuration template for customers to adapt their requirements. 2 adaptation modes are available including 'Low Network Bandwidth' and 'High Accuracy Clock'.\n\n\
'Low Network Bandwidth' options are suitable particulary for user who are strictly concern the efficiency of network data transmission and CPU loading.; On the other hand, 'High Accuracy Clock' options are used under circumstances where the timer is highly reliable.\n\n \
NOTE: 'High Accuracy Clock' not only minimize the Pdelay & Delay request interval, but also sets the delay of the generation of driver receive interrupts.  Receive interrupt reduction can improve CPU efficiency if properly tuned for specific network traffic.
Press SPACE to toggle an option on/off." 25 100 5 \
        "Low Network Bandwidth"  "(LNB mode) Reduces your network bandwidth/CPU" `if [ "$adaptive" == "Low Network Bandwidth" ]; then echo "ON"; else echo "off" ; fi` \
        "High Accuracy Clock"  "(HAC mode) Increace the clock accuracy" `if [ "$adaptive" == "High Accuracy Clock" ]; then echo "ON"; else echo "off" ; fi` 2> $tempfile
retval=$?

choice=`cat $tempfile`
case $retval in
  0)
    echo "'$choice' chosen.";
    ${INI_PARSER} -s system -n adaptive -v "$choice";;
  255)
    echo "ESC pressed.";
esac

AdvancedMenu
}

function ServoMenu() {
ap=`${INI_PARSER} -s servo -n ap -d 1`
ai=`${INI_PARSER} -s servo -n ai -d 10`
ad=`${INI_PARSER} -s servo -n ad -d 1`
$DIALOG --title "PID Servo Settings" --clear \
        --inputbox "PID Servo tunning stands for proportional, integral, derivative control mechanism. Under normal circumstances, user are not adviced to tune servo variables unless you fully understand P,I,D controller. The default PID controller is set to 1,10,1.\n
You can use BACKSPACE to correct errors. \n\n
Use comma as delimeter, e.g 1,10,1" 20 80 "$ap,$ai,$ad" 2> $tempfile


retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ap=`echo $choice|cut -d ',' -f 1`;
    ai=`echo $choice|cut -d ',' -f 2`;
    ad=`echo $choice|cut -d ',' -f 3`;
    ${INI_PARSER} -s servo -n ap -v $ap;
    ${INI_PARSER} -s servo -n ai -v $ai;
    ${INI_PARSER} -s servo -n ad -v $ad;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function StiffnessMenu() {
owdf_stiffness=`${INI_PARSER} -s servo -n owdf_stiffness -d 6`
$DIALOG --title "Delay Filter Stiffness Setting" --clear \
        --inputbox "Allow user to set one way delay filter. Under normal circumstances, users are not adviced to tune stiffness variables unless you fully understand Moxa PTPd internal servo mechanism. The default delay stiffness is set to 6.\n
You can use BACKSPACE to correct errors. \n\n
Factor:" 20 80 6 2> $tempfile


retval=$?
choice=`cat $tempfile`

case $retval in
  0)
    ${INI_PARSER} -s servo -n owdf_stiffness -v $choice;;
  1)
    echo "Cancel pressed.";;
  255)
    if test -s $tempfile ; then
      cat $tempfile
    else
      echo "ESC pressed."
    fi
    ;;
esac
AdvancedMenu
}

function AdvancedMenu() {
	$DIALOG --clear --item-help --cancel-label "Exit" --title "Advanced Setting" \
	        --menu "Warning:\n\
Unless you fully understand the consequences of changing the advanced settings, you should not modify it without guidance.\n\n\
Moxa's PTPd provides advanced configurations for customers who fully understand PTPd protocol. The following options allow users to set the PTPd protocol and servo used by PTP daemon. \n\
	\n\n\
Choose the options:" 20 80 0 \
	        "Foreign Master" "Specify maximal number of foreign master records" "..." \
	        "P2P Interval" "specify p2p interval" "..." \
	        "E2E Interval" "specify e2e interval" "..." \
	        "TTL" "multicast time to live" "..." \
	        "Domain" "specify domain" "..." \
	        "Select Enviroment Mode" "specify PTPd & driver enhance mode" "..." \
	        "Clock Offset Filter" "enable/disable clock offset filter" "..." \
	        "Delay Offset Filter" "delay offset filter" "..." \
	        "PID Servo" "specify P,I,D servo numeric" "..." \
	        "Delay Filter Stiffness" "specify owf stiffness numeric" "..." 2> $tempfile

	choice=`cat $tempfile`;
	case $choice in
	 	"P2P Interval")
	 		echo "OK 'advanced' chosen.";
	 		P2PIntervalMenu;;
	 	"E2E Interval")
	 		echo "OK 'advanced' chosen.";
	 		E2EIntervalMenu;;
	 	"TTL")
	 		echo "OK 'advanced' chosen.";
	 		MulticastTTLMenu;;
		"Foreign Master")
	 		echo "Apply pressed.";
	 		ForeignMasterMenu;;
		"Clock Offset Filter")
	 		echo "Apply pressed.";
	 		ClockOffsetFilterMenu;;
		"Delay Offset Filter")
	 		echo "Apply pressed.";
	 		DelayOffsetFilterMenu;;
		"Domain")
	 		echo "Apply pressed.";
	 		DomainMenu;;
		"UTC Offset")
	 		echo "Apply pressed.";
	 		UtcOffsetMenu;;
		"Select Enviroment Mode")
	 		echo "Apply pressed.";
	 		SelectEnviromentModeMenu;;
		"PID Servo")
	 		echo "Apply pressed.";
	 		ServoMenu;;
		"Delay Filter Stiffness")
	 		echo "Apply pressed.";
	 		StiffnessMenu;;
		*)
	 		echo "Unrecognize options";;
	esac
}

function CompleteWizardMenu() {
$DIALOG --title "Wizard" --clear \
        --msgbox "Congratulations! You have finished the PTPd settings!! \
                  Press ENTER to return to Main Menu" 10 41
case $? in
  0)
    echo "OK";;
  255)
    echo "ESC pressed.";;
esac
    MainMenu;
}

function SelectEnviromentWizardMenu() {
adaptive=`${INI_PARSER} -s system -n adaptive -d "High Accuracy Clock"`
$DIALOG --backtitle "Environmental Adaptation Selection" \
	--title "Select mode" --clear  --ok-label "Finish"\
        --radiolist "Moxa's DA-683 provids a powerful configuration template for customers to adapt their requirements. 2 adaptation modes are available including 'Low Network Bandwidth' and 'High Accuracy Clock'.\n\n\
'Low Network Bandwidth' options are suitable particularly for users who concern the efficiency of network data transmission and CPU loading. On the other hand, 'High Accuracy Clock' options are used under circumstances where the timer is highly reliable.\n\n \
NOTE: 'High Accuracy Clock' not only minimize the Pdelay & Delay request interval, but also sets the delay of the generation of driver receive interrupts.  Receive interrupt reduction can improve CPU efficiency if properly tuned for specific network traffic.
Press SPACE to toggle an option on/off." 25 100 5 \
        "Low Network Bandwidth"  "(LNB mode) Reduces your network bandwidth/CPU" `if [ "$adaptive" == "Low Network Bandwidth" ]; then echo "ON"; else echo "off" ; fi` \
        "High Accuracy Clock"  "(HAC mode) Increases the clock accuracy" `if [ "$adaptive" == "High Accuracy Clock" ]; then echo "ON"; else echo "off" ; fi` 2> $tempfile
retval=$?

choice=`cat $tempfile`
case $retval in
  0)
    echo "'$choice' chosen.";
    ${INI_PARSER} -s system -n adaptive -v "$choice";
    if [ "$choice" == "Low Network Bandwidth" ] ; then
    	${INI_PARSER} -s p2p -n delay -v 5;
    	${INI_PARSER} -s e2e -n delay -v 5;
        ${INI_PARSER} -s system -n max_foreign_record -v 2;
    else
    	${INI_PARSER} -s p2p -n delay -v 0;
    	${INI_PARSER} -s e2e -n delay -v 0;
        ${INI_PARSER} -s system -n max_foreign_record -v 5;
    fi
    CompleteWizardMenu;;
  1)
    echo "Cancel pressed.";
    SelectModeWizardMenu;;
  255)
    echo "ESC pressed.";
    MainMenu;; 
esac
}

function SelectModeWizardMenu() {
e2e_mode=`${INI_PARSER} -s system -n e2e_mode -d 0`
$DIALOG --backtitle "PTPd Protocol Selection" \
	--title "Select Mode" --clear  --ok-label "Next"\
        --radiolist "For the switches and routers that have implemented transparent clocks, either the end-to-end (E2E) method or peer-to-peer (P2P) method must be selected.\n\n\
In addition to providing PTP event transit time information, the peer-to-peer transparent clock (P2P TC) is a transparent clock that provides corrections for the propagation delay of the link connected to the port receiving the PTP event message. In the presence of peer-to-peer transparent clocks, delay measurements between slave clocks and the master clock are performed using the peer delay measurement mechanism.\n\n\
An end-to-end transparent clock (E2E TC) only measures the time taken for a PTP event message to transit the device and provides this information to clocks receiving this PTP event message.An end-to-end transparent clock (E2E TC) only measures the time taken for a PTP event message to transit the device and provides this information to clocks receiving this PTP event message.\n\n\
Press SPACE to toggle an option on/off." 25 100 5 \
        "P2P"  "P2P mode." `if [ "$e2e_mode" == "2" ]; then echo "ON"; else echo "off" ; fi` \
        "E2E"    "E2E mode." `if [ "$e2e_mode" == "1" ]; then echo "ON"; else echo "off" ; fi` 2> $tempfile
retval=$?

choice=`cat $tempfile`
case $retval in
  0)
    echo "'$choice' chosen.";
    if [ $choice == "P2P" ] ; then
	val=2
    else
	val=1
    fi
    ${INI_PARSER} -s system -n e2e_mode -v $val;
    SelectEnviromentWizardMenu;;
  1)
    echo "Cancel pressed.";
    SelectInterfaceWizardMenu;;
  255)
    echo "ESC pressed.";
    MainMenu;;
esac
}

function SelectInterfaceWizardMenu() { 
ether=`${INI_PARSER} -s system -n interface -d eth6`
$DIALOG --backtitle "Network Interface Selection" \
	--title "Select Interface" --clear  --ok-label "Next"\
        --radiolist "Moxa's DA-683 is a PTPd slave, it's ethernet ports are fully support PTP version 2 message hardware time stamping. Check the label located at DA-683 Ethernet where you connect to boundary clock or master clock, and select the appropriate port number that suits your environment.\n\n\
Press SPACE to toggle an option on/off." 25 100 5 \
        "eth6"  "IEEE1588 ethernet LAN 6" `if [ "$ether" == "eth6" ]; then echo "ON"; else echo "off" ; fi` \
        "eth7"  "IEEE1588 ethernet LAN 7" `if [ "$ether" == "eth7" ]; then echo "ON"; else echo "off" ; fi` \
        "eth8"  "IEEE1588 ethernet LAN 8" `if [ "$ether" == "eth8" ]; then echo "ON"; else echo "off" ; fi` \
        "eth9"  "IEEE1588 ethernet LAN 9" `if [ "$ether" == "eth9" ]; then echo "ON"; else echo "off" ; fi` 2> $tempfile
retval=$?

choice=`cat $tempfile`
case $retval in
  0)
    echo "'$choice' chosen.";
    ${INI_PARSER} -s system -n interface -v $choice;
    SelectModeWizardMenu;;
  1)
    echo "Cancel pressed.";
    MainMenu;;
  255)
    echo "ESC pressed.";
    MainMenu;;
esac
}

function WizardMenu() {
$DIALOG --title "Wizard" --clear --ok-label "Next"\
        --msgbox "Welcome to PTPd wizard!\n\
With a simplified Installation Wizard, configuring PTPd protocol is more straightforward and efficient than ever before.\n\n\ Press ENTER to continue" 10 41
case $? in
  0)
    echo "OK";
    SelectInterfaceWizardMenu;;
  255)
    echo "ESC pressed.";
    MainMenu;;
esac
}

function MonitorClockMenu() {

left=10
unit="seconds"
sleep 2 #wait for ptpd.log prepare
while test $left != 0
do
	RAW_RECORD=`tail -n 1 $PTPD_LOG`
	MEAN_PATH_DELAY=`echo $RAW_RECORD |cut -d ',' -f 4`
	# simple data protect over here
	echo $MEAN_PATH_DELAY |grep "^[0-9]" > /dev/null;
	if [ "$?" == "1" ]; then
		$DIALOG --sleep 1 \
			--title "Information invalid" "$@" \
		        --infobox "The information of current ptpd
		is not correct. Please check your setting."
		break ;
	fi
SYSTEM_TIMESTAMP=`echo $RAW_RECORD | cut -d ',' -f 1`
PTPD_STATE=`echo $RAW_RECORD |cut -d ',' -f 2`
PORT_IDENTITY=`echo $RAW_RECORD |cut -d ',' -f 3`
MEAN_PATH_DELAY_CALCULATE=`echo "$MEAN_PATH_DELAY * 1000000000"|bc|cut -d '.' -f 1`
SLAVE_TO_MASTER=`echo $RAW_RECORD |cut -d ',' -f 5`
SLAVE_TO_MASTER_CALCULATE=`echo "$SLAVE_TO_MASTER * 1000000000"|bc|cut -d '.' -f 1`
MASTER_TO_SLAVE=`echo $RAW_RECORD |cut -d ',' -f 6`
MASTER_TO_SLAVE_CALCULATE=`echo "$MASTER_TO_SLAVE * 1000000000"|bc|cut -d '.' -f 1`
CLOCK_DRIFT=`echo $RAW_RECORD |cut -d ',' -f 7`
CLOCK_DRIFT_CALCULATE=`echo "$CLOCK_DRIFT * 1000000000"|bc|cut -d '.' -f 1`
CLOCK_VARIANCE=`echo $RAW_RECORD |cut -d ',' -f 8`
SLAVE_TO_MASTER_OFFSET=`echo $RAW_RECORD |cut -d ',' -f 5 | cut -d '.' -f 2`
	
$DIALOG --sleep 1 --title "Precision Time Protocol Monitoring" "$@" --infobox "This monitoring tool allows you to analyze data from a number of timer sources. 
The data hence are used for collecting and analyzing IEEE 1588 packet-timing.
Wait a few moments, data is being reading......\n\n
	
$left $unit back to previous menu.\n\n\
	Current System Time Stamp     : $SYSTEM_TIMESTAMP \n\n
	PTPD State                    :$PTPD_STATE \n\n
	Port Identity                 :$PORT_IDENTITY \n\n
	Mean Path Delay               : $MEAN_PATH_DELAY_CALCULATE ns \n\n
	Slave to Master Offset        : $SLAVE_TO_MASTER_CALCULATE ns \n\n
	Master to Slave Offset        : $MASTER_TO_SLAVE_CALCULATE ns \n\n
	Clock Drift                   : $CLOCK_DRIFT_CALCULATE ns \n\n
	Clock Variance                :$CLOCK_VARIANCE ns \n\n" 35 72
left=`expr $left - 1`
test $left = 1 && unit="second"
done

MonitorMenu
}

function MonitorMenu() {
        $DIALOG --clear --item-help --cancel-label "Exit" --title "MOXA SYSTEM IEEE1588 SLAVE" \
                --menu " The slave process is able to change the setting in real-time process. Change the options below to adapt your enviroment. \n\
        \n\n\
Choose the options:" 20 80 0 \
                "Clock Information"  "Monitoring variances clock information"    "..." 2> $tempfile

        choice=`cat $tempfile`;
        case $choice in
                "Clock Information")
                        echo "OK 'Clock information' chosen.";
                        MonitorClockMenu;;
                "Internal Error Message")
                        echo "OK 'Analysis Purpose' chosen.";
                        InternalUsagePurposeMenu;;
                *)
                        echo "Clean ui setting... $retval";;
        esac

MainMenu
}


function ApplyMenu() {
background="Do not turn off your power or pause the program!!"
state=0
mstate=7 
pstate=7 
rstate=7 
ERR=0
i=0
while [ $i != 100 ] ;
do
$DIALOG --backtitle "$background" \
	--title "Processing your setting" \
	--mixedgauge "Do not turn off your power or pause the program!!" \
		0 0 $i \
		"Mounting"	"$mstate" \
		"Probing"	"$pstate" \
		"Restart"	"$rstate" \
		"Processing"	"-$i"
	case $state in
	  0)
	    #mount -o remount,rw /
	    cp -rf $DUMMY_INI_FILES $REAL_INI_FILES
	    sync
	    if [ $? == 1 ]; then
	    	ERR=1
		mstate=2
	    else
		state=1
		mstate=5
		i=30
	    fi ;;
	  1)
    	    driver_mode=`${INI_PARSER} -s system -n adaptive -d "High Accuracy Clock"`
	    if [ "$driver_mode" == "Low Network Bandwidth" ] ; then
	    	sed -i '/^options e1000e/ d' ${MODULE_FILES} 2> /dev/null ; echo "options e1000e" >> ${MODULE_FILES}
	    else
	    	sed -i '/^options e1000e/ d' ${MODULE_FILES} 2> /dev/null ; echo "options e1000e RxAbsIntDelay=0 RxIntDelay=0 InterruptThrottleRate=0 TxIntDelay=0" >> ${MODULE_FILES}
	    fi
	    #umount /
	    rmmod e1000e
	    modprobe e1000e

	    if [ $? == 1 ]; then
	    	ERR=1
		pstate=2
	    else
		state=2
		pstate=5
		i=50
	    fi ;;
	  2)
   	    killall ptpd2 2> /dev/null ;
	    for intf in ${INTERFACES}; do 
		ifdown ${intf} 2> /dev/null; 
		ifup ${intf} 2> /dev/null; 
	    done
   	    ptpd2;
	    if [ $? == 1 ]; then
	    	ERR=1
		rstate=2
	    else
		state=255
		rstate=5
		i=90
	    fi ;;
	  255)
		i=100
		sleep 1;
		break ;;
	esac
sleep 1 
done

if [ $ERR == 0 ]; then
	MSG="New PTPd setting & driver parameters have been set to your system successfully!!"
else
	MSG="Unable to apply PTPd. We recommend that you set the system back to factory default, and try again!!"
fi
$DIALOG --title "Applying PTPd & Driver Settings" --clear --ok-label "Next"\
        --msgbox "$MSG\n
\n\n Press the ENTER key to continue" 10 41
case $? in
  0)
    echo "OK";;
  255)
    echo "ESC pressed.";;
esac
MainMenu
}

# START HERE -----
# PREPARE DUMMY FILE BECAUSE SYSTEM IN R_ONLY MODE
cp -rf $REAL_INI_FILES $DUMMY_INI_FILES
# FOREVER LOOP UNTIL RETURN EXIT(1)
while [ 1 ] ; do
	MainMenu
done

