#!/usr/bin/env racket
#lang racket
(require srfi/98)
(require net/uri-codec)
(require net/smtp)

(define ERROR-HEADER "Location: register-fail\n\n")
(define SUCCESS-HEADER "Location: register-success\n\n")
(define FRIENDLY-MESSAGE #<<EOF
Thank you for registering in the OpenCL contest. Your information has been recorded.

We'll be emailing you with further details as the registration deadline approaches.
EOF
)

(define (is-user? str) (equal? (list str) (regexp-match #rx"[A-Za-z0-9._]+" str)))
(define (is-email? str) (equal? (list str) (regexp-match #rx"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+" str)))

(define required-fields `( (quest . ,is-user?) (email . ,is-email?)))
(define check-fields '(team open closed))

(define (identity x) x)

(let*
  ((post-data (form-urlencoded->alist (port->string)))
   (required-extract
     (map
       (lambda(x) (let ((e (assoc (car x) post-data)))
                       (cond [(false? e) #f]
                             [((cdr x) (cdr e)) e]
                             [else #f])))
       required-fields))
   (check-extract (filter identity (map ((curryr assoc) post-data) check-fields)))
   (filled-out? (andmap identity required-extract)))
  (when (not filled-out?)
    (printf ERROR-HEADER)
    (exit 0))
  (smtp-send-message
    "caffeine.csclub.uwaterloo.ca"
    "opencl-contest-registration@csclub"
    (list "init512@gmail.com")
    "Subject: Contestant registered!\n\n"
    (list (with-output-to-string
      (lambda() (write (append required-extract check-extract))))))
  (smtp-send-message
    "caffeine.csclub.uwaterloo.ca"
    "exec@csclub.uwaterloo.ca"
    (list (cdr (assoc 'email required-extract)))
    "Subject: OpenCL Registration Received\n\n"
    (list FRIENDLY-MESSAGE))
  (printf SUCCESS-HEADER)
  (exit 0))

