#!/usr/bin/python -u
#
# Check the sources for up2date
#

import string
import os
from sourcesConfig import SourcesConfigFile
import urlparse
import rhn_utils

class AppletSourcesConfigFile(SourcesConfigFile):
    """The applet source parser reuses the up2date parser except it
       avoid using the default configuration which may not be
       accessible as a normal user."""
    def __init__(self, filename = None):
        self.repos = []
	self.fileName = filename
	self.cfg = None  # do not load the up2date conf
	if self.fileName:
	    self.load()

    #
    # We don't need to resolve the URL for the applet to work
    # taht parsing code is changed
    #
    def parseUp2date(self,line):
        try:
            (tmp, url) = string.split(line)
        except:
            print "Error parsing /etc/sysconfig/rhn/up2date"
            print "at line: %s" % line
            return
            
	self.repos.append({'type':'up2date', 'url':url})
        

global sources
sources = None
global __sources_timestamp
__sources_timestamp = 0;
def getSources():
    """Load the RHN source definition file /etc/sysconfig/rhn/sources
       and returns a preparsed set of source repositories."""
    global sources
    global __sources_timestamp
    filename = "/etc/sysconfig/rhn/sources";

    try:
	stamp = os.stat(filename)[8]
	if sources and __sources_timestamp == stamp:
	    return sources
	scfg = AppletSourcesConfigFile(filename=filename)
	sources = scfg.repos
	__sources_timestamp = stamp
    except:
        rhn_utils.log_debug("Failed to read sources from %s, assuming up2date only" % ("/etc/sysconfig/rhn/sources"))
        sources = [{'url': 'default', 'type': 'up2date'}]
    return sources

def changedSources():
    """Check if the RHN source definition file /etc/sysconfig/rhn/sources
       have changed since the last call to getSources()."""
    global __sources_timestamp
    filename = "/etc/sysconfig/rhn/sources";

    try:
	stamp = os.stat(filename)[8]
	if __sources_timestamp == stamp:
	    return 0
    except:
        rhn_utils.log_debug("Failed to stat %s" % ("/etc/sysconfig/rhn/sources"))
    return 1
	    
    
