#!/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 not f.has_key('new') or f['new'].value != 'on' or \
    os.access(passwdfile, os.F_OK):
        Redirect(kLoginPage)

argstring = '%s %s %s' % (username, passwd, passwdfile)
Write2file ("newlogin.log", "Calling CreateUser with " + argstring)
CreateUser(username, passwd, passwdfile)
Write2file ("newlogin.log", "post CreateUser")

# 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)
