#!/usr/bin/python
# 
# hwdb upload server script
# 2005 Oliver Grawert (ogra) <hostmaster@grawert.net>

import cgi
import sys
import os
import re

# set globals
savepath='./'
targetpath='../'
pattern =  re.compile(r"^[a-z0-9.]{40}$") # allow only letters, digits and dots

tot_raw = open('./total.txt', 'r')
totals = tot_raw.read()
totals = int(totals)+1

dly_raw = open('./today.txt', 'r')
dly_tot = dly_raw.read()
dly_tot = int(dly_tot)+1


print "Content-Type: text/html\n"
cgidata = cgi.FieldStorage()

# show the form if there is no input yet

if not cgidata:
    print '\
    <span style="display:none;">\n\
    <form action="http://hwdb.ubuntu.com/upload/" method="post" enctype="multipart/form-data">\n\
    <input type="file" name="myfile" accept="text/plain" maxlength="2097152">\n\
    </form>\n\
    </span>'
    sys.exit(1)
 
file = cgidata["myfile"].file
filename = cgidata["myfile"].filename

# check for filename length and forbidden chars (a tribute to pitti)

if not pattern.search(filename):
    print '<h2>Error ! </h2><small>please contact <a href="mailto:\
    		hwdb@ubuntu.com">hwdb@ubuntu.com</a></small>'
    sys.exit(1)

fname = savepath+filename
outfile = open(fname, 'w')

# write the output file

for data in file.read():
    outfile.write(data)
outfile.close()

# move the data

os.system('mv '+fname+' '+targetpath)

tot_out = open('./total.tmp', 'w')
tot_out.write(str(totals))
os.system('mv ./total.tmp ./total.txt')

dly_out = open('./today.tmp', 'w')
dly_out.write(str(dly_tot))
os.system('mv ./today.tmp ./today.txt')

os.system('echo '+filename+' >> ./list.txt')
