# vim: fileencoding=latin2

import socket

Dependencies = ['host']

def change_pass(host, user, oldpass, newpass):
    port=106
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    data = s.recv(1024)
    if data[0]=='2':
        s.send('user %s\r\n'%user)
        data = s.recv(1024)
        if data[0]=='2':
            s.send('pass %s\r\n'%oldpass)
            data = s.recv(1024)
            if data[0]=='2':
                s.send('newpass %s\r\n'%newpass)
                data = s.recv(1024)
    s.close()
    return data

def execute(macro, args):
    request = macro.request
    formatter = macro.formatter
    _ = request.getText
    username = request.form.get('popusername', [''])[0]
    oldpass = request.form.get('poppassword', [''])[0]
    newpass1 = request.form.get('popnewpassword1', [''])[0]
    newpass2 = request.form.get('popnewpassword2', [''])[0]
    msg = ''
    if not username:
        msg = u'Please enter the username and all 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"The new password doesn't match -- please enter the same password twice."
    elif not len(newpass1)>=6:
        msg = u'The new passowrd must be at least 6 characters long.'
    else:
        msg = change_pass(args, username, oldpass, newpass1)
        if msg[0]=='2':
            msg = u'Password for <strong>%s</strong> has been changed.' % username
    html = [
        u'<form method="post" action="" enctype="application/x-www-form-urlencoded" class="poppass" name="poppass">',
        u'<p class="popmessage">', msg, u'</p>'
        u'<label>Username: <input type="text" name="popusername"></label>',
        u'<label>Current password: <input type="password" name="poppassword"></label>',
        u'<label>New password: <input type="password" name="popnewpassword1"></label>',
        u'<label>Repeat new password: <input type="password" name="popnewpassword2"></label>',
        u'<input type="submit" name="submit" value="Change" action="submit">',
        u'</form>',
    ]
    return formatter.rawHTML('\n'.join(html));
