#!/usr/bin/python
# This module provides functions for interacting with the Mac OS X Server
# 'servermgrd' backend. This is the same backend that Server Admin utilizes.
# This script requires superuser privledges.

import os
import plistlib
import StringIO

# buildXML creates an xml request for a servermgrd module.
# ** command is the name of the command to put in the request
# e.g. getHistory
# ** variant is an optional parameter for that command.
# e.g. "v1+v2" Use the servermgrd web interface to
# discover these; https://your.server:311
# ** timescale defines how many data samples to return (when applicable)
def buildXML ( command, variant, timescale ) :
  request = """<?xml version="1.0" encoding="UTF-8"?>
<plist version="0.9">
<dict>
	<key>command</key>
	<string>"""
  request = request + command
  request = request + '</string>'
  if timescale != '' :
    request = request + """
	<key>timeScale</key>
	<integer>"""
    request = request + timescale
    request = request + '</integer>'
  if variant != '' :
    request = request + """
	<key>variant</key>
	<string>"""
    request = request + variant
    request = request + '</string>'
  request = request + """
</dict>
</plist>"""
  return request

# sendXML sends the provided xml request to the specified servermgrd module,
# and returns a parsed plist object in dict form (from plistlib)
def sendXML ( servermgrdModule, request ) :
  modulePath = '/usr/share/servermgrd/cgi-bin/'+servermgrdModule
  pipeIn, pipeOut = os.popen2(`modulePath`)
  print >>pipeIn, request
  pipeIn.close()
  xmlresult = pipeOut.read(20480)
  pipeOut.close()
  xmlFauxFile = StringIO.StringIO(xmlresult)
  return plistlib.Plist.fromFile(xmlFauxFile)
