## dateBackend.py - provides the backend for system date calls
## Copyright (C) 2001, 2002, 2003 Red Hat, Inc.
## Copyright (C) 2001, 2002, 2003 Brent Fox <bfox@redhat.com>
##                                Tammy Fox <tfox@redhat.com>

## 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., 675 Mass Ave, Cambridge, MA 02139, USA.

import os
import time
import string
import socket

class dateBackend:
    def __init__(self):
        self.ntpFile = None
        self.ntpServer = None
        self.readNtpConf()
        pass

    def getDate (self):
        times = time.localtime(time.time())
        return times

    def writeDateConfig (self, sysDate, sysTime):
        year, month, day = sysDate
        hour, min, sec = sysTime

        #--cal.get_date starts counting months at 0 for Jan.  We need to start counting at 1
        month = month + 1
        path = '/bin/date -s %d/%d/%d' % (year,month,day)
        fd = os.popen(path, 'r')
        lines = fd.readlines()
        fd.close()

        path = '/bin/date -s %s:%s:%s' % (hour,min,sec)
        fd = os.popen(path, 'r')
        lines = fd.readlines()
        fd.close()


    def syncHardwareClock(self):
        # sync hardware clock.  Will use either localtime or utc
        # according to value in /etc/adjtime (recorded last time hwclock
        # was run).
        if os.access("/sbin/hwclock", os.F_OK) == 1:
            #The S390 has no hwclock binary, so don't try to run it if it isn't there
            os.system("/sbin/hwclock --systohc")

    def writeNtpConfig (self, timeServer, ntpServerList):
        serverFound = 0
        restrictFound = 0
        ntpFileList = []
        
        #Write /etc/ntp.conf file
        if self.ntpFile:
            for line in self.ntpFile:
                try:
                    serverIP = socket.gethostbyname(timeServer)
                except:
                    return None

                location = string.find(line, 'server')
                #If "server" is found in the line
                if location == 0:
                    tokens = string.split(line)

                    #If the line doesn't begin with a '#', then we're good
                    if tokens[0][0] != "#" and tokens[0] == "server" and not serverFound:
                        ntpFileList.append("server " + serverIP + "\n")
                        serverFound = 1

                    else:
                        #Else the line must either be a comment or some other abberation
                        #Just add the line so we preserve comments
                        ntpFileList.append(line)
                else:
                    restrict = string.find(line, 'restrict')
                    if restrict == 0:
                        #If 'restrict' is found in the line
                        tokens = string.split(line)

                        if tokens[0][0] != "#" and tokens[0] == "restrict" and not restrictFound:
                            if tokens[1] == "default":
                                ntpFileList.append(line)
                                ntpFileList.append("restrict %s mask 255.255.255.255 nomodify notrap noquery\n"
                                                   % serverIP)
                                restrictFound = 1
                            elif tokens[1] == "127.0.0.1":
                                ntpFileList.append(line)
                        else:
                            ntpFileList.append(line)

                    else:
                        #This is not the server line, so just add it to the list
                        ntpFileList.append(line)

            if not serverFound:
                #No server line was found in ntp.conf, which is a litte strange to begin with.
                #Anyway, just write out the whole file and append the server line to the end
                ntpFileList.append("server " + timeServer + "\n")

            #Now that we've got the list of data, open the file and write it out
            fd = open("/etc/ntp.conf", "w")

            for line in ntpFileList:
                fd.write(line)
            fd.close()

        else:
            fd = open("/usr/share/system-config-date/ntp.template", "r")
            lines = fd.readlines()
            fd.close()

            fd = open("/etc/ntp.conf", "w")

            for line in lines:
                if line[:6] == "server":
                    fd.write("server " + timeServer + "\n")
                else:
                    fd.write(line)
            fd.close()

        #Write /etc/ntp/step-tickers file
        if timeServer:
            fd = open("/etc/ntp/step-tickers", "w")
            fd.write(timeServer + "\n")
            fd.close()

        #Write /etc/ntp/ntpservers file
        if ntpServerList:
            fd = open("/etc/ntp/ntpservers", "w")
            for server in ntpServerList:
                fd.write(server + "\n")
            fd.close()

        return 0
    
    def startNtpService (self, wait):
        if self.isNtpRunning() == 1:
            fullPath = '/sbin/service ntpd restart > /dev/null'
        else:
            fullPath = '/sbin/service ntpd start > /dev/null'
        path = "/sbin/service"
        args = [path, "ntpd", "restart"]

        retval = os.system(fullPath)
        return retval
        
    def chkconfigOn(self):
        path = ('/sbin/chkconfig --level 35 ntpd on')
        os.system (path)
        
    def chkconfigOff(self):
        path = ('/sbin/chkconfig --level 35 ntpd off')
        os.system (path)

    def stopNtpService (self):
        if self.isNtpRunning() == 1:
            path = ('/sbin/service ntpd stop > /dev/null')
            os.system (path)
            path = ('/sbin/chkconfig --level 35 ntpd off')
            os.system (path)
        
    def isNtpRunning (self):
        if not os.access("/etc/ntp.conf", os.R_OK):
            #The file doesn't exist, so return
            return 0

        command = ('/sbin/service ntpd status > /dev/null')

        result = os.system(command)

        try:
            if result == 0:
                #ntpd is running
                return 1
            else:
                #ntpd is stopped
                return 0
        except:
            #we cannot parse the output of the initscript
            #the initscript is busted, so disable ntp
            return None
            
    def getNtpServer(self):
        serverFound = 0

        if self.ntpFile:
            for line in self.ntpFile:
                location = string.find(line, 'server')

                if location == 0:
                    tokens = string.split(line)
                    
                    if tokens[0][0] != "#" and tokens[0] == "server" and not serverFound:
                        try:
                            self.ntpServer = tokens[1]
                            serverFound = 1
                        except:
                            #They have a server line in /etc/ntp.conf with no server specified
                            self.ntpServer = None

            if self.ntpServer == "127.127.1.0" or self.ntpServer == None:
                return None
            else:
                return self.ntpServer

    def readNtpConf(self):
        try:
            fd = open('/etc/ntp.conf', 'r')
            self.ntpFile = fd.readlines()
            fd.close()
        except:
            return

    def readServersFile(self):
        self.ntpServerList = []
        if os.access("/etc/ntp/ntpservers", os.R_OK) == 1:
            fd = open("/etc/ntp/ntpservers", "r")
            lines = fd.readlines()
            for line in lines:            
                line = string.strip(line)
                if line and line[0] != "#":
                    self.ntpServerList.append(line)
            return self.ntpServerList
        else:
            return [""]
