#!/usr/bin/python # Copyright 2007 Dan Smith import ConfigParser import devices class Location: def __init__(self, config, name): self.name = name # Required keys self.caption = "" self.subnet = None self.devices = [] # Extra properties self.auxprops = {} for k,v in config.items(name): if k == "caption": self.caption = v elif k == "subnet": self.subnet = v elif k == "devices": self.devices = v.split() else: self.auxprops[k] = v def amIHere(self, dev): if self.devices: if dev.getName() not in self.devices: return False if self.subnet: if self.subnet not in dev.getIP4Address(): return False return True def auxStrings(self): s = [] for k,v in self.auxprops.items(): s.append("%s=%s" % (k, v)) return s def __str__(self): base = "%s: %s\n %s\n %s\n" % (self.name, self.caption, self.subnet, self.devices) aux = "" for k,v in self.auxprops.items(): aux += " %s = %s" % (k,v) return base + aux class LocationFactory: def __init__(self, config_file): self.config = ConfigParser.ConfigParser() self.config.read(config_file) def locations(self): locations = [] for loc in self.config.sections(): if loc != "default": locations.append(Location(self.config, loc)) return locations class LocationService: def __init__(self, config_file): self.config_file = config_file def current_location(self): locs = LocationFactory(self.config_file).locations() dev = devices.NetworkDeviceFactory().getDefaultDevice() for loc in locs: if loc.amIHere(dev): return loc if __name__ == "__main__": import sys lf = LocationFactory(sys.argv[1]) for loc in lf.locations(): print loc print "" ls = LocationService(sys.argv[1]) print ls.current_location()