#!/usr/bin/env python2
# coding=utf-8

import cgi
import cgitb
import re
import smtplib
import uuid
import datetime
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
cgitb.enable()

CONTACT_EMAIL_TO = 'kontakt@freifunk-bs.de'

EMAIL_REGEX = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"

print "Content-Type: text/html"
print ""

template = """<meta charset="utf-8">\n%s<br>\n<a href="/kontakt.html">zurück</a>"""
form = cgi.FieldStorage()

try:
    email = form['email'].value
    if not re.match(EMAIL_REGEX, email):
        raise ValueError()
    message = form['message'].value
    
    captcha = form['captcha'].value
    captcha = captcha.replace("'", "")
    captcha = captcha.replace('"', "")
    captcha = captcha.strip()

    today = str(datetime.datetime.now().day)
    if today == captcha:
        msg = MIMEText(message, 'plain', 'utf-8')
        msg['From'] = "kontakt@freifunk-bs.de"
        msg['To'] = CONTACT_EMAIL_TO
        msg['Subject'] = 'Kontaktanfrage von %s' % email
        msg['Reply-To'] = ','.join([email,CONTACT_EMAIL_TO])
        uuid = str(uuid.uuid4()) #get a random uuid
        msg['Message-ID'] = '<'+uuid+'@freifunk-bs.de>'
        p = Popen(["/usr/sbin/sendmail", "-t", "-oi", "-FKontaktformular"], stdin=PIPE)
        p.communicate(msg.as_string())
        print template % "Ihre Nachricht wurde entgegengenommen"
    else:
        msg = MIMEText(message, 'plain', 'utf-8')
        msg['From'] = "kontakt@freifunk-bs.de"
        msg['To'] = CONTACT_EMAIL_TO
        msg['Subject'] = '[CAPTCHA]Kontaktanfrage von %s' % email
        msg['Reply-To'] = ','.join([email,CONTACT_EMAIL_TO])
        uuid = str(uuid.uuid4()) #get a random uuid
        msg['Message-ID'] = '<'+uuid+'@freifunk-bs.de>'
        msg['X-FFBS-CAPTCHA'] = "Failed: User tried: {}; I expected: {}".format(captcha, today)
        p = Popen(["/usr/sbin/sendmail", "-t", "-oi", "-FKontaktformular"], stdin=PIPE)
        p.communicate(msg.as_string())
        print template % "Der Spamschutz wurde nicht erfolgreich ausgefüllt. Bitte versuchen Sie es erneut."
except Exception as e:
    print template % "Die Anfrage ist ungültig"