#!/bin/bash

## script to insert as root crontab to run daily after 0600 to set
## ntp sysconfig slew mode to handle 2015 leap second addition on
## June 30, 2015 for affected older systems identified as vulnerable
## in https://www.suse.com/support/kb/doc.php?id=7016150

test $EUID -eq 0  || {  ## validate EUID
    printf "error: '%s' requires UID/EUID = 0 (i.e. you must be root)\n" \
    "${0##*/}" >&2
    exit 1
}

syscfg_dir=/etc/sysconfig       ## set ntp & backup related path/filenames
test -f "${syscfg_dir}/ntp" && syscfg_ntp="${syscfg_dir}/ntp"
test -f "${syscfg_dir}/xntp" && syscfg_ntp="${syscfg_dir}/xntp"

syscfg_ntp_bak="${syscfg_ntp}.bak"
syscfg_ntp_orig="${syscfg_ntp}.orig"
# bufile_ntp="${syscfg_dir}/ntp_leapsec_2015.cfg" ## unused - delete

test -w "$syscfg_dir" || {      ## validate required cfg dir & file
    printf "error: dir not writeable. '%s'\n" "$syscfg_dir" >&2
    exit 1
}

test ! -z "$syscfg_ntp" || {
    printf "error: file not found. sysconfig/ntp (or xntp)\n" >&2
    exit 1
}

opt_cfg=NTPD_OPTIONS            ## set config option & get original options
opt_orig=$(grep "$opt_cfg" "$syscfg_ntp")

cmd_restart="$(type -p rcntp) restart"   ## set restart command

declare -i dt_now=$(date +%s)   ## set dates for setting/removing slew
declare -i dt_629=$(date -d "2015-06-29 06:00:00" +%s)
declare -i dt_701=$(date -d "2015-07-01 06:00:00" +%s)

test -z "$opt_orig" -o -z "$cmd_restart" && {   ## validate
    printf "error: opt_orig or cmd_restart has no value.\n" >&2
    exit 1
}

test -z "$dt_now" -o -z "$dt_629" -o -z "$dt_701" && {
    printf "error: dt_now, dt_629 or dt_701 has no value.\n" >&2
    exit 1
}

## if after 6/29 and before 7/1 (at 0600) and slew not set
#  set slew & save original config & restart ntp
if test $dt_701 -gt $dt_now -a $dt_now -gt $dt_629 -a ! -f "$syscfg_ntp_orig" ; then
    cp -a "$syscfg_ntp" "$syscfg_ntp_orig"
    sed -i.bak '/^NTPD_OPTIONS/s/^\(NTPD_OPTIONS="\)\(.*$\)/\1-x \2/' "$syscfg_ntp"
    test -f "$syscfg_ntp_bak" ||
        printf "error: sed backup creation failed, original in '%s'\n" \
        "$syscfg_ntp_orig" >&2
    $cmd_restart
fi

## if after 7/1 reset ntp sysconfig options to original
#  and remove backup files & restart ntp
if test $dt_now -gt $dt_701 ; then
    if test -f "$syscfg_ntp_bak" ; then
        cp -a "$syscfg_ntp_bak" "$syscfg_ntp"
        rm "$syscfg_ntp_bak"
        test -f "$syscfg_ntp_orig" && rm -f "$syscfg_ntp_orig"
        $cmd_restart
    elif test -f "$syscfg_ntp_orig" ; then
        cp -a "$syscfg_ntp_orig" "$syscfg_ntp"
        rm "$syscfg_ntp_orig"
        $cmd_restart
    else
        printf "error: neither '%s' or '%s' available\n" \
        "$syscfg_ntp_bak" "$syscfg_ntp_orig"
        printf "       manually reconfigure/restart ntp.\n"
    fi
fi

exit 0
