# vim: fileencoding=latin2

import os, re

Dependencies = ['host']

def change_pass(host, user, oldpass, newpass):
    if not re.match(r'^[A-Za-z0-9]+$', user):
        return 'Bad username!'
    if not re.match(r'^[.a-z0-9-]+$', host):
        return 'Bad host name!'
    (inf, errf) = os.popen4('''/usr/bin/smbpasswd -r '%s' -U '%s' -s'''%(host, user), 'rw')
    inf.write('%s\n'%oldpass)
    inf.write('%s\n'%newpass)
    inf.write('%s\n'%newpass)
    inf.close()
    msg = errf.read()
    errf.close()
    return msg

def execute(macro, args):
    request = macro.request
    formatter = macro.formatter
    _ = request.getText
    username = request.form.get('smbusername', [''])[0]
    oldpass = request.form.get('smbpassword', [''])[0]
    newpass1 = request.form.get('smbnewpassword1', [''])[0]
    newpass2 = request.form.get('smbnewpassword2', [''])[0]
    msg = ''
    if not username:
        msg = u"Please enter the username and the passwords."
    elif not oldpass:
        msg = u"You didn;t enter your current password."
    elif not (newpass1 and newpass2):
        msg = u"You didn't enter your new password twice."
    elif not newpass1==newpass2:
        msg = u"New password must be repeated twice. Make sure it's the same.'
    elif not len(newpass1)>=7:
        msg = u'New password must be at least 7 characters long.'
    else:
        msg = change_pass(args, username, oldpass, newpass1)
    html = [
        u'<form method="post" action="" enctype="application/x-www-form-urlencoded" class="poppass" name="smbpass">',
        u'<p class="popmessage">', msg, u'</p>'
        u'<label>Username: <input type="text" name="smbusername"></label>',
        u'<label>Current password: <input type="password" name="smbpassword"></label>',
        u'<label>New password: <input type="password" name="smbnewpassword1"></label>',
        u'<label>Repeat new password: <input type="password" name="smbnewpassword2"></label>',
        u'<input type="submit" name="submit" value="Change" action="submit">',
        u'</form>',
    ]
    return formatter.rawHTML('\n'.join(html));
