#!/usr/bin/python
import cgi, string, array, crypt, sys
from utils import *
from cookie import *
from konst import *

f = cgi.FieldStorage()

if not f.has_key('login') or not f.has_key('passwd'):
    Redirect(kLoginPage)

username = f['login'].value
passwd = f['passwd'].value

sys.stderr = sys.stdout
# new account...
passwdfile = '%s%s/.passwd' % (kReportsDir, username)

if f.has_key('new') and f['new'].value == 'on':
    if os.access(passwdfile, os.F_OK):
        # error ... already exists
        Redirect(kLoginPage)
    CreateUser(username, passwd, passwdfile)

    # create dummy default data files for faster use later...
    # TODO if the user changes these sections we need to cleanup these
    # files!
    for k in kDefFiles:
        Write2file('%s%s/%s' % (kReportsDir, username, k), '')

    sects=''
    for k in range(len(kDefFiles)):
        sects = sects + '%s: %s\n' % (kDefFiles[k], kDefSections[k])

    Write2file('%s%s/.prefs' % (kReportsDir, username),
        '[DEFAULT]\nsections: %s\nsubmitday: 4\n%s' % 
            (string.join(kDefFiles), sects))

    SetCookieForYear('user',username, '/reports/') 
    Redirect('%s%s' % (kBaseLocation, 'prefs.cgi'))

if ValidUser(username, passwd, passwdfile):
    SetCookieForYear('user',username, '/reports/') 
    Redirect(kBaseLocation)
else:
    Redirect(kLoginPage, 4, """<h2>Login failed!</h2> Redirecting you back to
the login page! Contact <a href="mailto:leaf">leaf</a> if you have forgotten
your passwd.""")
