#!/bin/sh

conffile=/etc/default/adjtimex
startfile=/etc/init.d/adjtimex

echo -n "Comparing clocks (this will take 70 sec)... "

# Get the parameters

/sbin/adjtimex  --tick 10000 --frequency 0
/sbin/adjtimex --adjust >/etc/adj.adjust
ticks=`tail -1 /etc/adj.adjust|awk '{print $6}'`
freq=`tail -1 /etc/adj.adjust|awk '{print $7}'`
rm /etc/adj.adjust
echo "adjusting system time by " `awk "BEGIN{print ($ticks-10000)*8.64+$freq/65536.*.0864}"` " sec/day"

# Recreate /etc/adjtimex.conf if necessary

if [ -f $conffile ]; then 
#   echo "using existing $conffile";
    true;
else 
cat >$conffile <<EOF
#  $conffile - configuration file for adjtimex(8)
#
#  you may adjust these values manually or by calling /usr/sbin/adjtimexconfig
#
#  This file is sourced by $startfile
#
TICK=$TICK
FREQ=$FREQ

EOF
fi

# Reset values in $conffile

sed -e "s/^TICK=.*/TICK=$ticks/"		\
    -e "s/^FREQ=.*/FREQ=$freq/"			\
    $conffile >$conffile.TMP &&			\
    mv $conffile.TMP $conffile

# grep "TICK=" /etc/init.d/adjtimex | cut -d'#' -f1 > /etc/adj.tick
# grep "FREQ=" /etc/init.d/adjtimex | cut -d'#' -f1 > /etc/adj.freq
# 
# TICKLINE="`echo -n "TICK="$ticks" # old: "; cat /etc/adj.tick`"
# FREQLINE="`echo -n "FREQ="$freq" # old: "; cat /etc/adj.freq`"
# 
# cp /etc/init.d/adjtimex /etc/init.d/adjtimex.TMP
# sed -e "s/^TICK=.*/$TICKLINE/" -e "s/^FREQ=.*/$FREQLINE/" \
#  < /etc/init.d/adjtimex.TMP > /etc/init.d/adjtimex
# 
# if [ -s /etc/init.d/adjtimex ]
# then
# 	  rm -f /etc/init.d/adjtimex.TMP
# fi
# rm -f /etc/adj.tick /etc/adj.freq /etc/adj.adjust
rm -f /etc/adj.adjust

echo "Done"
