module Main where

import Network.CGI
import Data.Maybe
import System.IO

import DB
import Process
import Session
import Now
import FancyHtml

main = runCGI $ handleErrors cgiMain

cgiMain = do
    sessionId <- getInput "session_id"
    recipient <- getInput "recipient"
    subject   <- getInput "subject"
    message   <- getInput "message"
    validsess <- liftIO $ check_session_id $ fromJust sessionId
    user      <- liftIO $ get_session_user $ fromJust sessionId
    if (validsess)
        then sendMessage user (fromJust recipient) (fromJust subject) (fromJust message)
        else output $ header ++ errorBox "Incorrect session ID, go away!" ++ footer

sendMessage sender recipient subject message = do
    -- cert_data <- liftIO $ run "echo 'foo'"
    cert_data <- liftIO $ db_firstvalue $ "SELECT data FROM certificates WHERE subject LIKE '" ++ recipient ++ "'"
    -- write certificate to temp file
    (certfile, certhandle) <- liftIO $ openTempFile "/tmp" "cert"
    liftIO $ hPutStr certhandle cert_data
    liftIO $ hClose certhandle
    -- create encrypted message
    encrypted_message <- liftIO $ run_with_stdin ("openssl smime -encrypt -to '" ++ recipient ++ "' -from '" ++ sender ++ "' -subject '" ++ subject ++ "' " ++ certfile) message
    -- save message to DB
    now_isodate    <- liftIO $ now
    message_digest <- liftIO $ run_with_stdin "openssl dgst -sha256" message
    let sep = "','"
    liftIO $ db_insert $ "INSERT INTO messages VALUES ('" ++ sender ++ sep ++ recipient ++ sep ++ subject ++ sep ++ message ++ sep ++ encrypted_message ++ sep ++ now_isodate ++ sep ++ (chomp message_digest) ++ "')"
    output $ header ++ "Thank you for using encrypted messaging. Your (encrypted) message has been published. The message digest is " ++ (chomp message_digest) ++ "." ++ (quote "Unix and C are the ultimate computer viruses." "http://www.schnada.de/quotes/contempt.html" "Richard P. Gabriel") ++ footer
