#!/usr/bin/bash
#######################
# Override the default ntp.conf with one containing non-'pool' NTP servers.
# Only replaces the ntp.conf if it finds the 'pool' servers in the ntp.conf so
# it shouldn't matter if it is an upgrade or a new install.
#######################

grep pool /etc/ntp.conf &> /dev/null
if [ $? == 0 ]; then
cat >/etc/ntp.conf <<EOF
logfile /var/log/ntpd
driftfile /var/lib/ntp/ntp.drift
statsdir  /var/lib/ntp/
statistics loopstats peerstats clockstats
filegen loopstats file loopstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable

# You should have at least 4 NTP servers

server owamp.atla.net.internet2.edu iburst
server navobs1.gatech.edu iburst
server navobs1.wustl.edu iburst
server now.okstate.edu iburst
server ntp-s1.cise.ufl.edu iburst
server time-a-g.nist.gov iburst
server time-b-g.nist.gov iburst
server time-c-wwv.nist.gov iburst
server time-d-wwv.nist.gov iburst
server chronos.es.net iburst
server saturn.es.net iburst
server time1.ethz.ch iburst
server vega.cbk.poznan.pl iburst
server tempus1.gum.gov.pl iburst
server tick.usask.ca iburst
server tock.usask.ca iburst
server ntp.time.nl iburst
server ntp.se iburst
EOF
fi

grep restrict /etc/ntp.conf &> /dev/null
if [ $? != 0 ]; then
cat >>/etc/ntp.conf <<EOF
# by default act only as a basic NTP client
restrict -4 default nomodify nopeer noquery notrap
restrict -6 default nomodify nopeer noquery notrap
# allow NTP messages from the loopback address, useful for debugging
restrict 127.0.0.1
restrict ::1
EOF
fi

####################
# Configure default NTP servers for first boot.
####################

file=/etc/ntp/step-tickers

if [ ! -s $file ]; then
cat >$file <<EOF
owamp.atla.net.internet2.edu
navobs1.gatech.edu
navobs1.wustl.edu
now.okstate.edu
ntp-s1.cise.ufl.edu
time-a-g.nist.gov
time-b-g.nist.gov
time-c-wwv.nist.gov
time-d-wwv.nist.gov
chronos.es.net
saturn.es.net
time1.ethz.ch
vega.cbk.poznan.pl
tempus1.gum.gov.pl
tick.usask.ca
tock.usask.ca
ntp.time.nl
ntp.se
EOF
fi


####################
# Auto-select NTP servers based on proximity
####################
if [ "$1" == "new" ]; then
    /usr/lib/perfsonar/scripts/autoselect_ntp_servers
fi

##################################
# Enable ntpd and disable chronyd
##################################
if type systemctl &>/dev/null; then
    systemctl disable chronyd 2>/dev/null
    systemctl stop chronyd 2>/dev/null
    systemctl enable ntpd 2>/dev/null
    systemctl stop ntpd 2>/dev/null
    systemctl start ntpd 2>/dev/null
else
    /sbin/chkconfig ntpd on 2>/dev/null
    /etc/init.d/ntpd stop 2>/dev/null
    /etc/init.d/ntpd start 2>/dev/null
fi
