#!/bin/bash

### This script is used for automation and remediaton of ntp alerts across Newfold digital ###
### Please note  requirements of this code before running it  ###
### ntpdate utility should be present on server  ###
### service should be enabled in init check config and and systemd for this to work, remediations will not happen for services which are in disable state
os_check=$(cat /etc/*release | grep "^ID=" | awk  -F "=" '{print$2}'| tr -d '"')
os_cent6_check=$(cat /etc/redhat-release  | awk '{print tolower($1)}' | uniq)
if [[ $os_check == ubuntu ]];then
    config=ntp
    config_chrony=chrony
    conf_service=ntp
    systempath="/bin/systemctl"

elif [[ $os_check == "centos" ]] || [[ $os_check == "rhel" ]] || [[ $os_cent6_check == "centos" ]] || [[ $os_cent6_check == "red" ]] || [[ $os_cent6_check == "cloudlinux" ]] ;then
    config=ntp
    conf_service=ntpd
    config_chrony=chronyd
    systempath="/usr/bin/systemctl"
else
    config=ntpd
    conf_service=ntpd
fi

ntp_server_init () {
    for i in $(grep  ^server /etc/"$config".conf  | awk '{print $2}') ; do  ntpdate -u "$i";
        if [[  $? == "0" ]]; then
            break;
        fi;
    done
    /etc/init.d/"$conf_service" restart 
}

ntp_server_systemd () {
service_ntp_status=$($systempath is-enabled "$conf_service" 2>/dev/null)
service_chronyd_status=$($systempath is-enabled "$config_chrony" 2>/dev/null)
    if  [[ "$service_chronyd_status" == "enabled" ]]; then
        systemctl restart "$config_chrony"
    elif [[ "$service_ntp_status" == "enabled" ]] ; then
        for i in $(grep  ^server /etc/"$config".conf  | awk '{print $2}') ; do  ntpdate -u "$i";
            if [[  $? == "0" ]]; then
            break;
            fi;
        done
        systemctl restart $conf_service ;
    else
        echo "Services are in disabled state, nothing to remediate please contact service Delivery"
    fi
}
serv_type=$(cat /proc/1/comm)
case $serv_type in

  "init")
    ntp_server_init
    ;;
   "systemd")
    ntp_server_systemd
    ;;
   *)
    echo -n "Not included in this case, report to Service delivery"
    ;;
esac
