#!/usr/bin/python
## -*- coding: utf-8 -*-
#
# Copyright © 2006 Clodoaldo Pinto Neto cpn@codepoint.net
#
# All code, and only the code, in webpython.codepoint.net is free software; 
# you can redistribute it and/or modify it under the terms of the GNU General
# Public License as published by the Free Software Foundation; either version
# 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this application; if not, write to the Free Software Foundation, Inc., 51
# Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##################################################################################

import cgi, os
import cgitb; cgitb.enable()
import sys

UPLOADDIR='files/'

form = cgi.FieldStorage()

# Get filename here.
fileitem = form['filename']

# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid 
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   ## Check filename matches expected values
   print """\Content-Type: text/html\n"""
   if os.path.isfile(UPLOADDIR + fn):
     message = "ERROR: File Exists"
     EXIT=1
   elif not fn.endswith(".tar.gz") or not fn.endswith(".barelog"):
     message = "ERROR: File is invalid"
     EXIT=2
   else:
     open(UPLOADDIR + fn, 'wb').write(fileitem.file.read())
     message = fn + ' was uploaded successfully'
     EXIT=0
else:
   message = 'No file was uploaded'
   
#print """\Content-Type: text/html\n"""
print """%s""" % (message,)
sys.exit(EXIT)



