#!/bin/sh -e
#
#  Copyright (C) 2015 ScyllaDB

print_usage() {
    echo "scylla_ntp_setup -a"
    echo "  -a  AMI instance mode"
    exit 1
}

AMI=0
while getopts a OPT; do
    case "$OPT" in
        "a")
            AMI=1
            ;;
        "h")
            print_usage
            ;;
    esac
done

. /etc/os-release
if [ "$NAME" = "Ubuntu" ]; then
    apt-get install -y ntp ntpdate
    service ntp stop
    ntpdate `cat /etc/ntp.conf |grep "^server"|head -n1|awk '{print $2}'`
    service ntp start
else
    yum install -y ntp ntpdate || true
    if [ $AMI -eq 1 ]; then
        sed -e s#centos.pool.ntp.org#amazon.pool.ntp.org# /etc/ntp.conf > /tmp/ntp.conf
        mv /tmp/ntp.conf /etc/ntp.conf
    fi
    if [ "`systemctl is-active ntpd`" = "active" ]; then
        systemctl stop ntpd.service
    fi
    ntpdate `cat /etc/ntp.conf |grep "^server"|head -n1|awk '{print $2}'`
    systemctl enable ntpd.service
    systemctl start ntpd.service
fi
