#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
. $SCRIPT_DIR/common.sh "$@"


echo "-- SETTING UP NTP --------------------------------------------------------------"

if [[ $IS_MASTER == 1 ]]; then

    echo " - Configuring master NTP server"
    # hetzner ntp servers
    sudo sed -i s/"pool 0.debian.pool.ntp.org iburst"/"pool ntp1.hetzner.de iburst"/g /etc/ntp.conf
    sudo sed -i s/"pool 1.debian.pool.ntp.org iburst"/"pool ntp2.hetzner.com iburst"/g /etc/ntp.conf
    sudo sed -i s/"pool 2.debian.pool.ntp.org iburst"/"pool ntp3.hetzner.net iburst"/g /etc/ntp.conf
    sudo sed -i s/"pool 3.debian.pool.ntp.org iburst"/""/g /etc/ntp.conf

fi

if [[ $IS_SLAVE == 1 ]]; then

    echo " - Configuring slave NTP server"
    # hetzner ntp servers
    sudo sed -i s/"pool 0.debian.pool.ntp.org iburst"/"#pool ntp1.hetzner.de iburst"/g /etc/ntp.conf
    sudo sed -i s/"pool 1.debian.pool.ntp.org iburst"/"#pool ntp2.hetzner.com iburst"/g /etc/ntp.conf
    sudo sed -i s/"pool 2.debian.pool.ntp.org iburst"/"#pool ntp3.hetzner.net iburst"/g /etc/ntp.conf
    sudo sed -i s/"pool 3.debian.pool.ntp.org iburst"/"\nserver $MASTER_IP"/g /etc/ntp.conf

    sudo sed -i s/"restrict -4 default kod notrap nomodify nopeer noquery limited"/"#restrict -4 default kod notrap nomodify nopeer noquery limited"/g /etc/ntp.conf
    sudo sed -i s/"restrict -6 default kod notrap nomodify nopeer noquery limited"/"#restrict -6 default kod notrap nomodify nopeer noquery limited"/g /etc/ntp.conf

    sudo bash -c "echo -e \"\n\n#enabling mes_master to set time\" >> /etc/ntp.conf"
    sudo bash -c "echo \"restrict $MASTER_IP mask 255.255.255.255 nomodify notrap nopeer noquery\" >> /etc/ntp.conf"

    sudo bash -c "echo -e \"\n\n#disable maximum offset of 1000 seconds\" >> /etc/ntp.conf"
    sudo bash -c "echo \"tinker panic 0\" >> /etc/ntp.conf"

fi

# restarting ntp
echo " - restarting ntp"
sudo systemctl restart ntp > /tmp/setup_ntp_log 2>&1
fail_if_error $? "/tmp/setup_ntp_log" -1

