#!/bin/bash

VNLK="timeout -k 31 30 /usr/bin/vnlk"
CENTOS=0
UBUNTU=0
CHRONY_BIN=/usr/sbin/chronyd
CHRONY_SVC=chrony
CHRONY_CONF=/etc/chrony/chrony.conf
CHRONY_CONF_TMP=/tmp/chrony.conf.tmp

function log {
    local level=${2-info}
    echo >&2 -e "[$(date +"%Y-%m-%d %H:%M:%S")] ${1-}"
    logger -p local0.${level} -t check-time-daemon "${1-}"
}

function die {
    local msg=$1
    local code=${2-1}
    log "$msg" error
    exit $code
}

function prepare {
    # Get OS
    if grep -q "Ubuntu" /etc/os-release; then
        UBUNTU=1
    elif grep -q "CentOS" /etc/os-release; then
        CENTOS=1
        CHRONY_CONF=/etc/chrony.conf
        CHRONY_SVC=chronyd
    fi
    # Do nothing if we aren't running on neither Centos nor Ubuntu
    if [[ $CENTOS -eq 0 && $UBUNTU -eq 0 ]]; then exit 0; fi
    # Do nothing if chronyd isn't installed
    if [ -z "$(which $CHRONY_BIN)" ]; then
        log "Chrony is not installed"
        exit 0
    fi
}

function get-node-ip {
    $VNLK -rx "link show status" | grep ^Node: | awk '{print $2}' 2>/dev/null
}

function get-endpoint {
    $VNLK -rx "link show status" | grep ^Endpoint: | awk '{print $2}' 2>/dev/null
}

function configure-time-daemon {
    local nodeip="$(get-node-ip)"
    local endpoint="$(get-endpoint)"
    local restart=0
    if [ -z "$nodeip" ]; then
        die "Cannot get node ip"
    fi
    if [ -z "$endpoint" ]; then
        die "Cannot get cluster endpoint"
    fi

    if [ $UBUNTU -eq 1 ]; then
        # disable systemd-timesyncd if enabled
        if /usr/bin/systemctl status systemd-timesyncd >/dev/null
        then
            /usr/bin/systemctl stop systemd-timesyncd
            /usr/bin/systemctl disable systemd-timesyncd 2>/dev/null
        fi
    else
        # disable ntpd if enabled
        if /usr/bin/systemctl status ntpd >/dev/null
        then
            /usr/bin/systemctl stop ntpd
            /usr/bin/systemctl disable ntpd 2>/dev/null
        fi
    fi

    # Add node IP as ntp server to the chronyd config
    [ -f $CHRONY_CONF_TMP ] && unlink $CHRONY_CONF_TMP
    cp -f $CHRONY_CONF $CHRONY_CONF_TMP
    # If previous endpoint differs from current one, remove all existing "server" entries
    prev_endpoint="$(grep JSEP: $CHRONY_CONF_TMP  | awk '{print $3}')"
    if [ "$prev_endpoint" != "$endpoint" ]; then
        log "Endpoint has changed: $prev_endpoint => $endpoint"
        echo "# JSEP: $endpoint" >> $CHRONY_CONF_TMP
        perl -pi -e "s/^server .* port 30123 prefer//" $CHRONY_CONF_TMP
    fi
    if ! grep -q "^server $nodeip" $CHRONY_CONF_TMP; then
        echo "server $nodeip iburst port 30123 prefer" >> $CHRONY_CONF_TMP
    fi
    if ! grep -q "^allow" $CHRONY_CONF_TMP; then
        echo "allow" >> $CHRONY_CONF_TMP
    fi
    if ! diff -q $CHRONY_CONF $CHRONY_CONF_TMP; then
        mv -f $CHRONY_CONF_TMP $CHRONY_CONF
        restart=1
    fi

    # enable chronyd
    if ! /usr/bin/systemctl status $CHRONY_SVC >/dev/null
    then
        /usr/bin/systemctl restart $CHRONY_SVC
        /usr/bin/systemctl enable $CHRONY_SVC
        restart=0
    fi

    # restart chronyd if config has been changed
    if [ $restart -eq 1 ]; then
        log "Chronyd config has been changed. Restarting the service"
        systemctl restart $CHRONY_SVC
    fi
}

function main {
    prepare

    configure-time-daemon
}

main
