#!/usr/bin/python
import cgi, cgitb, sys
import MySQLdb
import dbname
cgitb.enable() # formats errors in HTML

sys.stderr = sys.stdout
print "Content-type: text/html"
print
print '''<html>
<head>
<title>Login</title>
</head>
<body>'''

login_form = '''<form action="login.py" method="POST">
<p>Please enter your username  and password
<p><table>
<tr><td>Username&nbsp;&nbsp;<td><input type="text" name="username">
<tr><td>Password<td><input type="password" name="password">
</table>
<p><input type="submit" value="Login">
</form>
</body></html>'''

form = cgi.FieldStorage()

fields = ["username", "password"]
errors = False

print '<dir><pre>'
for field in fields:
    if (not form.has_key(field)):
        print 'missing <b>%s</b>' % field
        errors = True
print '</pre></dir>'
if (errors):
    print login_form;
    sys.exit();

db = dbname.dbopen()
cur = db.cursor()

try:
    cur.execute("""SELECT fullname from users
        where username='%s' and password='%s'""" % (form["username"].value, form["password"].value) )
    rows = cur.fetchall()
    if (cur.rowcount > 0):
        print '<p>%s is logged on' % rows[0]
        ready = True
    else:
        print '<p>login failed, please try again.'
        ready = False
        
    cur.close()
    db.close()
except MySQLdb.Error, e:
    print e

if (not ready):
    print login_form
    sys.exit(1)

print '</body></html>'