#!/bin/bash
#
# Copyright (c) 2008 SUSE LINUX Products GmbH, Nuernberg, Germany.
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
#
# Author: Michael Calmer <mc@suse.de>
#         Marius Tomaschewski <mt@suse.de>
#
# $Id: $
#

if test "$UID" != "0" -a "$USER" != root -a -z "$ROOT" ; then
    echo "You must be root to start $0." >&2
    exit 1
fi

# The environment variable ROOT indicates the root of the system to be
# managed by SuSEconfig when that root is not '/'
r="$ROOT"

. "$r/etc/sysconfig/network/scripts/functions.netconfig"

PROGNAME="${0##*/}"
STATEDIR="$r/var/run/netconfig/"
debug "$PROGNAME Module called"

. "$r/etc/sysconfig/network/config"

NTP_SERVER_LIST=""

DESTFILE="$r/var/run/ntp/servers-netconfig"
TMP_FILE=""

function write_ntp_servers()
{
    if [ -z "$1" ]; then
        # empty list of ntp servers 
        # => remove the runtime configuration file
        rm -f $DESTFILE
        return 1
    fi

    debug "write_ntp_servers: $1"

    # make sure that the directory exists
    test -d "${DESTFILE%/*}" || {
	debug "no ${DESTFILE%/*} directory - skipping"
	return 1
    }

    local SERVERS

    TMP_FILE=`mktemp "$r/tmp/ntp-servers-netconfig.XXXXXX"` || return 1

    if test ! -s "$DESTFILE" ; then
        touch "$DESTFILE"  ; chmod 644 "$DESTFILE"
    fi

    # * copy dest => tmp to get the file attributes
    # * remove the content 
    # * print a warning on top of this file
    #cp -p "$DESTFILE" "$TMP_FILE"

    # set explicit mode on tmp file instead to preserve the
    # mode of original file that can be wrong (bnc#428458)
    chmod 644 "$TMP_FILE"

    cat << EOT > "$TMP_FILE"
### $DESTFILE file autogenerated by netconfig!
#
# Before you change this file manually, consider to define the
# static NTP configuration using the following variables in the
# /etc/sysconfig/network/config file:
#     NETCONFIG_NTP_STATIC_SERVERS
# or disable NTP configuration updates via netconfig by setting:
#     NETCONFIG_NTP_POLICY=''
#
# See also the netconfig(8) manual page and other documentation.
#
# Note: Manual change of this file disables netconfig too, but
# may get lost when this file contains comments or empty lines
# only, the netconfig settings are same with settings in this
# file and in case of a "netconfig update -f" call.
#
### Please remove (at least) this line when you modify the file!
EOT

    for ns in $1; do
	for os in ${SERVERS[@]} ; do
		[ "x$ns" == "x$os" ] && continue 2
	done

	SERVERS=(${SERVERS[@]} ${ns})
    done

    if [ ${#SERVERS[@]} -gt 0 ]; then
        echo "RUNTIME_SERVERS='${SERVERS[@]}'" >> "$TMP_FILE"
    fi

    netconfig_check_md5_and_move "$TMP_FILE" "$DESTFILE"
    return $?
}

function get_ntp_settings() {
    debug "exec get_ntp_settings: $1"
    test -z "$1" && return 1

    get_variable "NTPSERVERS" "$1"
    if [ "x$NTPSERVERS" != "x" ]; then
        NTP_SERVER_LIST="$NTP_SERVER_LIST $NTPSERVERS"
        NTPSERVERS=""
    fi

    debug "exit get_ntp_settings"
    return 0
}

function manage_interfaceconfig() {

    debug "manage_interfaceconfig: $1"

    test -z "$1" && return 1

    if [ ! -d "$1" ]; then
        return 1
    fi
    for CFG in `ls -X -r $1/`; do
        debug "CFG=$CFG"

        get_ntp_settings "$1/$CFG"

    done
    debug "exit manage_interfaceconfig"
    return 0
}

_NETCONFIG_NTP_POLICY="$NETCONFIG_NTP_POLICY"
if [ "$_NETCONFIG_NTP_POLICY" = "auto" ]; then
    if [ "x$NETWORKMANAGER" = "xyes" ] ; then
        #
        # Use NetworkManager policy merged data
        #
        _NETCONFIG_NTP_POLICY='STATIC_FALLBACK NetworkManager'
    else
        #
        # We try a static value for "auto"
        # if this is not enough we may add some magic later
        #
        _NETCONFIG_NTP_POLICY='STATIC *'
    fi
elif [ "x$_NETCONFIG_NTP_POLICY" = "x" ]; then
    #
    # empty policy means do not touch anything. 
    # successful exit.
    #
    exit 0;
fi
#
# A * or ? is evaluated in the "for loop", so we need to replace it  
#
_NETCONFIG_NTP_POLICY=`echo "$_NETCONFIG_NTP_POLICY" | \
        sed 's/\*/__ALL__/g' | sed 's/\?/__ONE__/g'`

sf=0

for POL in $_NETCONFIG_NTP_POLICY; do 
    case "$POL" in
    (NetworkManager)
        if [ "x$NETWORKMANAGER" = "xyes" ] ; then
            debug "Use NetworkManager policy merged settings"
            CFG="$STATEDIR/NetworkManager.netconfig"
            if [ -r "$CFG" ] ; then
                get_ntp_settings "$CFG"
            fi
            break
        fi
    ;;
    (STATIC)
        debug "Keep Static"
        NTP_SERVER_LIST="$NTP_SERVER_LIST $NETCONFIG_NTP_STATIC_SERVERS"
        ;;
        (STATIC_FALLBACK)
        debug "Static Fallback"
        sf=1
    ;;
    (*)
        #
        # revert the replacement; now we want the evaluation
        #
        POL=`echo "$POL" | sed 's/__ALL__/*/g' | sed 's/__ONE__/?/g'`
        debug "Other: $POL"
        for IFDIR in $STATEDIR/$POL; do
	    test -d "$IFDIR" -a \
	         -d "/sys/class/net/${IFDIR##*/}" || continue
            # proceed every interface we find with this match
            manage_interfaceconfig  "$IFDIR"
        done
    ;;
    esac
done

if [ $sf -eq 1 -a -z "$NTP_SERVER_LIST" ]; then
    NTP_SERVER_LIST="$NETCONFIG_NTP_STATIC_SERVERS"
fi

write_ntp_servers "$NTP_SERVER_LIST"
RET=$?

if [ $RET -eq 1 ]; then
    # nothing changed; we are finished
    exit 0
elif [ $RET -eq 2 ]; then
   # user modified the config. Copy aborted
    echo "ATTENTION: You have modified $DESTFILE.  Leaving it untouched..."
    echo "You can find my version in $TMP_FILE ..."

    exit 20
fi

# here we should restart services if needed

# try restart ntp; reload is not supported and we need 
#                  to delete old servers
if [ -x $r/etc/init.d/ntp ]; then
        $r/etc/init.d/ntp try-restart >/dev/null 2>&1
fi

exit 0;


