#!python
# -*- coding: utf-8 -*-
#
# 2015-10-12 Cornelius Kölbel <cornelius@privacyidea.org>
#            Rewrite to LDAP3
#
__version__ = "0.2"

import getpass
import sys
from getopt import GetoptError, getopt

import ldap3

# Objectclass for OpenLDAP
# OBJECT_CLASSES = ['top', "posixAccount", 'inetOrgPerson']
# ObjectClass for AD
OBJECT_CLASSES = ["top", "person", "inetOrgPerson", "user"]


def usage():
    print("""
    Parameter:
    -f <csv file>
    -h : help
    -u <ldap uri>
    -b <base, where to create the user>
    -d <Bind DN>
    """)


def create_user(l, base, keys, values):
    dn = "%s=%s,%s" % (keys[0], values[0], base)
    attrs = {}
    for x in range(1, len(keys)):
        attrs[keys[x]] = values[x]

    print("creating user %s" % dn)
    r = l.add(dn, object_class=OBJECT_CLASSES, attributes=attrs)
    if not r:
        print("   Failed to create user with attributes %s" % attrs)
        print(l.result)


def main():
    filename = None
    base = None
    uri = None
    bind = None

    try:
        opts, args = getopt(sys.argv[1:], "f:u:b:d:", ["file="])

    except GetoptError:
        print("There is an error in your parameter syntax:")
        usage()
        sys.exit(1)

    for opt, arg in opts:
        if opt in ("-f", "--file"):
            filename = arg
        elif opt in ("-b",):
            base = arg
        elif opt in ("-d",):
            bind = arg
        elif opt in ("-u",):
            uri = arg
        elif opt in ("-h", "--help"):
            usage()
            sys.exit(1)

    if not filename or not base or not uri or not bind:
        usage()
        sys.exit(2)
    else:
        password = getpass.getpass("Please enter password for %s: " % bind)

        # read the first line
        f = open(filename, "r")
        first_line = f.readline()
        keys = [x.strip() for x in first_line.split(",")]

        l = ldap3.Connection(
            uri,
            user=bind,
            password=password,
            auto_bind=True,
            authentication=ldap3.SIMPLE,
            check_names=True,
            auto_referrals=False,
        )
        # l.open()

        for line in f:
            values = [v.strip() for v in line.split(",")]
            create_user(l, base, keys, values)

        l.unbind()


if __name__ == "__main__":
    main()
