#!/opt/osstech/bin/python2.7
# -*- coding: utf-8 -*-

# unicornidm-schema-extend.py
#
# Copyright (C) TAMURA Kohei @ Open Source Solution Technology Co. Ltd.
# License: GNU General Public License version 2 or later
# Date: 2011-11-24

import os, subprocess, sys, pwd
from optparse import OptionParser

def main():
    UNICORNIDM_PATH = "/opt/osstech/lib/unicornIDM"
    UNICORNIDM_CMD = "%s/manage.py" % UNICORNIDM_PATH

    HTTPDUSER = "apache"

    try:
        webuser = pwd.getpwnam(HTTPDUSER)
    except KeyError, e:
        sys.stderr.write("user %s does not exist on this system.\n" % HTTPDUSER)

    ruid = os.getuid()
    if ruid != 0 and ruid != webuser.pw_uid:
        sys.stderr.write("You are not permited.\n")
        sys.exit(1)

    usage = "usage: %prog -t <target> -o <optype> -c <objectClass> -a <attributenames>"

    parser = OptionParser(usage=usage)
    parser.add_option("-t", "--target", dest="serverId", help="Target server id")
    parser.add_option("-o", "--optype", dest="opType", type="choice", choices=["add", "del"], help="Type of operation [add,del]")
    parser.add_option("-c", "--objectClass", dest="objectClass", help="objectClass Name")
    parser.add_option("-a", "--attributenames", dest="attributenames", help="attribute names of the objectclass")

    (opts, args) = parser.parse_args(sys.argv)

    if not args:
        parser.print_help()
        sys.exit(1)

    if not opts.serverId:
        sys.stderr.write("Target serverId is not specified.\n")
        parser.print_help()
        sys.exit(1)
    else:
        serverId = opts.serverId

    if not opts.opType:
        sys.stderr.write("Type of operation is not specified.\n")
        parser.print_help()
        sys.exit(1)
    else:
        opType = opts.opType

    if not opts.objectClass:
        sys.stderr.write("objectClass is not specified.\n")
        parser.print_help()
        sys.exit(1)
    else:
        objectClass = opts.objectClass

    if opType == "add":
        if not opts.attributenames:
            sys.stderr.write("attributenames is not specified.\n")
            parser.print_help()
            sys.exit(1)
        else:
            attributenames = opts.attributenames

    try:
        cmd = [UNICORNIDM_CMD, "extendschema", "-t", serverId, "-o", opType, "-c", objectClass, "-a", attributenames]
        p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=UNICORNIDM_PATH)
        stdstr = p.stdout.readlines()
        errstr = p.stderr.readlines()
        r = p.wait()

        if (r == 0):
            for line in stdstr:
                sys.stdout.write(line)
        else:
            # Fail to execute
            sys.stderr.write("Failed to extend schema. \n%s\n" % str(errstr))
            sys.exit(1)
    except Exception, e:
        sys.stderr.write("Failed to extend schema. \n%s\n" % str(e))
        sys.exit(1)

    return

main()
