#!/usr/bin/python
import cgi, traceback, sys, os, string, shutil
from cookie import *
from utils import *
from konst import *
from prefs import *

print 'Content-Type: text/html'

if not os.environ.has_key('HTTP_COOKIE'):
    Redirect(kLoginPage)

username = GetCookie('user')
if not username:
    Redirect(kLoginPage)

userdir = '%s%s' % (kReportsDir, username)
if not os.access(userdir, os.F_OK):
    os.makedirs(userdir)

sys.stderr = sys.stdout

prefs = Prefs('%s/.prefs' % userdir)

try:
    form = cgi.FieldStorage()
    splitchar = ' '
    if ',' in prefs.sectionorder: splitchar = ','
    for k in string.split(prefs.sectionorder, splitchar):
        if form.has_key(k): # we could get rid of this check but for the error
            Write2file('%s/%s' % (userdir, k), form[k].value)
    from autostats import update_bugs_stat
    update_bugs_stat(username, LastSubmitted(username))


    if form['perm'].value == '1':
        t = Today()
        backup = 0
        archdir = '%s/old/%s' % (userdir, t)
        if not os.access(archdir, os.F_OK):
            os.makedirs(archdir)
        else: # already exists back up...
            backup = 1

        for k in string.split(prefs.sectionorder, splitchar):
            if os.access('%s/%s' % (userdir, k), os.F_OK):
                if backup:
                    shutil.copy('%s/%s' % (archdir, k), '%s/%s.bak'
                        % (archdir, k))
                shutil.copy('%s/%s' % (userdir, k), archdir)
                # may not be relevant... 
                os.chmod('%s/%s' % (archdir, k), 400)
            # truncate all current files...
            Write2file('%s/%s' % (userdir, k), '')

        # Also update the autostats-
        # TODO check with a pref later on
        #from autostats import update_bugs_stat
        #update_bugs_stat(username)
        
        Redirect('%sshow.cgi?user=%s&viewtype=last' % 
            (kBaseLocation, username))

    Redirect('%sshow.cgi?user=%s&viewtype=current' %
            (kBaseLocation, username))

except:
    print '\n\n<H3>Oops! something bad happened... contact '
    print '<A HREF="mailto:leaf@mozilla.org">leaf</A></H3>'
    print '\n\n<PRE>'
    print '-'*60
    traceback.print_exc()
    print '-'*60
    print '\n</PRE>\n'

