#!/bin/bash

NTPD_BIN="/usr/sbin/ntpd"
if [ ! -x ${NTPD_BIN} ]; then
  zenity --error --text="Time server, ${NTPD_BIN} not installed!"
  exit 1
fi

/etc/init.d/ntp stop >/dev/null 2>&1

NTP_CONF=/etc/ntp.conf
if [ ! -f ${NTP_CONF} ]; then
	zenity --error --text="Time server configuration file, ${NTP_CONF} does not exist."
	exit 1
fi

if ! grep -v 127.127.1.0 $NTP_CONF | grep ^server >/dev/null; then
	zenity --error --text="No time server set in configuration file."
	exit 1
fi

/sbin/startproc $NTPD_BIN -g -u ntp:ntp -c $NTP_CONF -q

for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20; do
	per=`expr $i \* 5`
	echo "$per%"
	sleep 1;
	NTPDPID=`ps ax | awk '$5 ~ /\/usr\/sbin\/ntpd/ {print $1}'`
	if [ -z "$NTPDPID" ]; then
		break
	fi
done | zenity --progress --auto-close

NTPDPID=`ps ax | awk '$5 ~ /\/usr\/sbin\/ntpd/ {print $1}'`
if [ -z "$NTPDPID" ]; then
	zenity --info --text="Sync time with time server successfully."
	exit 0
else
	kill -9 $NTPDPID
	zenity --error --text=" No server reached"
	exit 1
fi



