#!/usr/bin/env python

# Written by Nedko Arnaudov

import sys
import os, time, sha, codecs
from random import randint
from getpass import getpass

# You need to change this
moin_instance_dir="/web/moin/resa"

datetime_fmt = '%Y-%m-%d %H:%M:%S'

def encodePassword(pwd, charset='utf-8'):
    """ Encode a cleartext password

    Compatible to Apache htpasswd SHA encoding.

    When using different encoding than 'utf-8', the encoding might fail
    and raise UnicodeError.

    @param pwd: the cleartext password, (unicode)
    @param charset: charset used to encode password, used only for
        compatibility with old passwords generated on moin-1.2.
    @rtype: string
    @return: the password in apache htpasswd compatible SHA-encoding,
        or None
    """
    import base64

    # Might raise UnicodeError, but we can't do anything about it here,
    # so let the caller handle it.
    pwd = pwd.encode(charset)

    pwd = sha.new(pwd).digest()
    pwd = '{SHA}' + base64.encodestring(pwd).rstrip()
    return pwd

class User:
    def __init__(self, username, password, email):
        self.aliasname=""
        self.css_url=""
        self.date_fmt=""
        self.datetime_fmt=""
        self.disabled="0"
        self.edit_on_doubleclick="0"
        self.edit_rows="20"
        self.editor_default="text"
        self.editor_ui="freechoice"
        self.language=""
        self.last_saved = str(time.time())
        self.mailto_author="0"
        self.quicklinks=""
        self.remember_last_visit="0"
        self.remember_me="1"
        self.show_fancy_diff="1"
        self.show_nonexist_qm="0"
        self.show_page_trail="1"
        self.show_toolbar="1"
        self.show_topbottom="0"
        self.subscribed_pages=""
        self.theme_name="modern"
        self.tz_offset="0"
        self.want_trivial="0"
        self.wikiname_add_spaces="0"

        self.id = "%s.%d" % (str(time.time()), randint(0,65535))

        self.name=username
        self.enc_password=encodePassword(password)
        self.email=email

    def save(self):
        filename = "%s/data/user/%s" % (moin_instance_dir, self.id)
        data = codecs.open(filename, "w")
        data.write("# Data saved '%s' for id '%s'\n" % (
            time.strftime(datetime_fmt, time.localtime(time.time())),
            self.id))

        attrs = vars(self).items()
        attrs.sort()
        for key, value in attrs:
            line = u"%s=%s\n" % (key, unicode(value))
            data.write(line)
        data.close()

        os.chmod(filename, 0660)

print "MoinMoin user creator"
print "====================="
print

if len(sys.argv) != 3:
    print "Usage: moin_useradd.py <username> <email>"
    sys.exit(0)

username = sys.argv[1]
email = sys.argv[2]

print "username: %s" % username
print "email: %s" % email

password = getpass("password: ")
password_again = getpass("password (again): ")

if password != password_again:
    print "Passwords does not match"
    sys.exit(0)

user = User(username, password, email)
user.save()
