#!/usr/bin/python
"""Bunch of utilities from gagzilla"""
import sys, time, crypt, os, string
# this should not be here... but for now for LastSubmitted
from konst import *
from cookie import *
from cgi import escape

def CreateUser(login, passwd, passwdfile):
    userdir = os.path.dirname(passwdfile)
    if not os.access(userdir, os.F_OK):
        os.makedirs(userdir)
    f = open(passwdfile, 'w')
    f.write(crypt.crypt(passwd, 'sr'))
    f.close()

def FatalError(msg):
    """Print the Error mesg and exit."""
    print "Error: " + msg
    try: sys.exit(0)
    except: pass

def IfElse(test, a, b):
    if test: return a
    else: return b

def LastFriday():
    if TGIF(): return Today()
    # Mon (0) = -3
    # Tue (1) = -4
    # Wed (2) = -5
    # Thu (3) = -6
    # Fri (4) = --
    # Sat (5) = -8
    # Sun (6) = -9
    delta = 3 + time.localtime(time.time())[6]
    if delta >7 : delta = delta - 7
    t = time.time() - delta*86400
    return time.strftime('%Y-%m-%d', time.localtime(t))

def LastSubmitted(username, lastweekonly=0, rel=0, reldt=''): # rel=1 for prev. 2 for next
    if not os.access('%s%s/old' % (kReportsDir, username), os.F_OK):
        return None
    try:
        if lastweekonly:
            # make this be python :-) TODO
            dirs = string.split(os.popen(
            'find %s%s/old -mtime -7 -maxdepth 1 -type d -printf \'%%P\n\'' % 
                    (kReportsDir, username)).read())
        else:
            dirs = os.listdir("%s%s/old" % (kReportsDir, username))
    except OSError:
        return None
    if not len(dirs):
        return None
    dirs.sort()
    if rel and reldt != '':
        if reldt not in dirs: 
            dirs.append(reldt)
            dirs.sort()
        for i in range(len(dirs)):
            if dirs[i] == reldt:
                if rel==2 and i<len(dirs)-1:
                    return dirs[i+1]
                elif rel==1 and i>0:
                    return dirs[i-1]
        return None
    return dirs[-1]

def MailMsg(to, subject, msg):
    import smtplib
    server = smtplib.SMTP(kMailHost)
    server.sendmail(kMailFrom, to,
        "From: (%s)\r\nTo: %s\r\nSubject: %s\r\nReply-To:%s\r\n\r\n%s" %
        (kMailFrom, to, subject, kReplyTo, msg))
    server.quit()

def PrintFile(file, bullets=0, showconf=1, esc=0):
    """Prints the said file as is"""
    from buglink import replace_bugs
    try: # ideally this should call PrintFile(ignore=0)
        # but it dumps core... :( so copy and paste from below...
        f=open(file,'r')
        if not bullets:
            dt = f.read()
            print IfElse(esc, escape(dt), dt)
        else:
            print '<UL>'
            line = replace_bugs(f.readline())
            while line:
                line = string.strip(line)
                if len(line) and (showconf or line[0] != '-'):
                    print '<LI>%s' % IfElse(line[0]=='-', line[1:], line)
                line = replace_bugs(f.readline())
            print '</UL>'
        f.close()
    except:
        pass

def Redirect(location, duration=0, mesg=''):
    host = os.environ['HTTP_HOST']
    if location[0] == '/': location = location[1:]
    print 'Location: http://%s/%s \n\n' % (host, location)
    print "Content-type: text/html\n\n"
    print """<HTML><HEAD><META HTTP-EQUIV="Refresh" 
CONTENT="%d; URL=http://%s/%s"> </HEAD> <body bgcolor="#DDDDDD"> %s </body></HTML>""" % (duration, host, location, mesg)
    sys.exit(0)

def TGIF():
    return TodayIs(4)

def TodayIs(day):
    if time.localtime(time.time())[6] == day: return 1
    else: return 0
    
def Today():
    """Returns todays date in YYYY-MM-DD format"""
    return time.strftime('%Y-%m-%d', time.localtime(time.time()))

def ValidUser(login, passwd, passwdfile):
    try:
        f = open(passwdfile, 'r')
        cryptedpasswd = f.read()
        f.close()
        return cryptedpasswd == crypt.crypt(passwd, 'sr')
    except:
        return 0

def Warning(msg):
    """Print the waring mesg and continue"""
    print "Warning: " + msg

def Write2file(file, data):
    f = open(file, 'w')
    if len(data):
        f.write(string.strip(string.replace(data, '\r\n', '\n')))
    else:
        # os.ftruncate(f, 0) # grrr not working... :-(
        f.write('')
    f.close()

