#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - batch user creation tool
GPL code written by TheAnarcat, december 2005

This tool allows batch creation of users in a wiki. You need to modify a few
settings below in order to get going, see below.

Generally, the idea is to populate a page with a list of users, or a
dictionnary (UserName:: email) of users, and run this script on it. See the -h
flag for more information.
"""

import sys, re

# ----------------------------------------------------------------------------
# CHECK THESE SETTINGS, then remove or comment out the following line:
#print "Check the settings in the script first, please!" ; sys.exit(1)

# this is where your moinmoin code is (if you installed it using
# setup.py into your python site-packages, then you don't need that setting):
#sys.path.insert(0, '/home/twaldmann/moincvs/moin--main')

# this is where your wikiconfig.py is:
wiki_url = '/usr/local/www/wiki/koumbitwiki'
sys.path.insert(0, wiki_url)

# if you include other stuff in your wikiconfig, you might need additional
# pathes in your search path. Put them here:
#sys.path.insert(0, '/org/wiki')

# This is the list of accounts to create
magicpage = "MembresDeKoumbit"

# ----------------------------------------------------------------------------

from MoinMoin.user import *
from MoinMoin import config, wikiutil, Page
from MoinMoin.scripts import _util
from MoinMoin.request import RequestCLI
from MoinMoin.wikidicts import Group, Dict
from os import popen3
from sys import stderr, stdout

def random_pass(passlen = 8):
    """Generate a random password using pwgen or some homebrewed recipe."""
    stdin, stdout, stderr = popen3(["pwgen"])
    out = stdout.readline() or ""
    if not out:
        from random import choice
        for i in range(passlen):
           out += chr(choice(range(ord('0'), ord('z'))))
    return out.strip()

def run():
    disableuser = save = dict = group = 0

    if "--disableuser" in sys.argv or "-d" in sys.argv:  disableuser = 1
    if "--save" in sys.argv or "-s" in sys.argv:  save = 1
    if "--group" in sys.argv or "-g" in sys.argv: group = 1
    if "--dict" in sys.argv or "-d" in sys.argv: dict = 1

    if "--help" in sys.argv or "-h" in sys.argv or not dict and not group:
        print """%s
Options:
        -d --disableuser    disable the user with user id uid
                            this can't be combined with the options above!
        -s --save           if specified, save the accounts to disk
                            if not specified, no user will be added
        -g --group          parse the list in the magicpage
        -d --dict           parse the dict in the magicpage

One of -g or -d must be specified.
    """ % sys.argv[0]
        return

    if wiki_url:
        request = RequestCLI(wiki_url)
    else:
        request = RequestCLI()

    # look for usernames to create in magicpage
    page = Page.Page(request, magicpage)
    if not page.exists():
        raise ValueError("page " + magicpage + " does not exist")

    # load users from the dict and/or groups in the magic page
    users = {}
    if dict:
        g = Dict(request, "Testgroup")
        g.initFromText(page.get_raw_body())
        users.update(g)
    if group:
        g = Group(request, "TestGroup")
        g.initFromText(page.get_raw_body())
        users.update(g)

    for username, email in users.iteritems():
        username = username.strip()
        u = User(request, None, username)
        # output a formal list of treated usernames
        stdout.write(" * " + u.name)
        # skip existing users
        if u.exists():
            stdout.flush()
            # mark skipped usernames on stderr so that the list is still valid
            stderr.write(" (skipped)")
            stdout.write("\n")
            continue

        # we need to recreate the user because the id will not be autogenerated
        # if the usesname is passed as arg
        u = User(request, None, None, random_pass())
        # set various parameters
        u.name = username
        u.disabled = disableuser
        if email != 1:
                u.email = email
        # close this line
        stdout.write("\n")
        if save:
            u.save()

    if not save:
        print "not saved"

if __name__ == "__main__":
    run()

# EOF