#!/usr/bin/python
#
# utility functions for RHN Configuration
# Copyright (c) 2002 Red Hat, Inc.
#  Distributed under GPL.
#
# Author: Adrian Likins <alikins@redhat.com>
#
#

import sys
import xmlrpclib
sys.path.append("/usr/share/rhn/up2date_client/")

import config
import rpcServer
import up2dateErrors
import up2dateAuth
import string
import os
import re

#cfg = config.initUp2dateConfig()

def getServerUrls():
    # NOTE: this method talks to the current serverURL
    # setting to ask for a list of other available servers
    cfg = config.initUp2dateConfig()

    # see if we have a systemid
    systemid = None
    if cfg['useRhn']:
        systemid = up2dateAuth.getSystemId()
    s = rpcServer.getServer()
    returnList = []
    serverUrls = []
    # just try this call once, since we may be behind a proxy
    cfg["networkRetries"] = 1
    try:
	if systemid:
            serverUrls = rpcServer.doCall(s.servers.list, systemid)
	else:
 	    serverUrls = rpcServer.doCall(s.servers.list)
    except xmlrpclib.Fault, f:
        if f.faultCode == -1:
            #this means were talking to a server that doesnt know this
            # call, shouldnt happen, but some satellites could do it
            print "this server does not implement the servers.list() call"
        else:
            # this is a little wrong... we tell the user there was a
            # fault, but keep on trucking...
            print """A xmlrpclib.fault was caught indicating there was
an error with the server. The error was: %s """ % f

        returnList = [cfg["serverURL"]]
    except up2dateErrors.CommunicationError:
	# we cant talk outsite the network yet, probabaly need
	# proxy stuff setup. 
	returnList = [cfg["serverURL"]]

    cfg["networkRetries"] = 5
    #serverUrls is a list of hashes

    # make sure we always list the master rhn server as per request
    masterserver = "xmlrpc.rhn.redhat.com"
    masterhandler = "/XMLRPC"
    masterflag = 0
    defaultflag = 0

    defaultUrl = cfg["serverURL"]

    
    for i in serverUrls:
        if i['server'] == masterserver and i['handler'] == masterhandler:
            masterflag = 1

    if not masterflag:
        serverUrls.append({'server': masterserver, 'handler':masterhandler})

    for i in serverUrls:
        returnList.append( "https://%s%s" % (i['server'], i['handler']) )

    if defaultUrl not in returnList:
        returnList.insert(0, defaultUrl)
        
    return returnList


def writeUp2dateMacro(macroName, macroValue):

    if os.access("/etc/rpm/macros.up2date", os.R_OK):
        f = open("/etc/rpm/macros.up2date", "r")
        lines = f.readlines()
        f.close()
    else:
        lines = []
    comment_r = re.compile("\s*#.*")
    value_r = re.compile("%s.*" % macroName)
    blank_r = re.compile("\s*")
    newfile = []
    for line in lines: 
        m = value_r.match(line)
        if m:
            continue

        m = comment_r.match(line)
        if m:
            newfile.append(line)
            continue

        newfile.append(line)
            
        # dont care about blank lines...

    newfile.append("\n")
    newfile.append("%s       %s" % (macroName, macroValue))


    f = open("/etc/rpm/macros.up2date", "w")
    for line in newfile:
        f.write(line)
    f.write("\n")
    f.close()

    
            
            
        

def main():
    writeUp2dateMacro("%__enableRollbacks", "blipppyfffffffff")
        #print getServerUrls()




if __name__ == "__main__":
    main()
