module Main where

import Network.CGI
import Text.XHtml
import Text.Regex.Posix
import Data.Maybe

import Process
import CertInfo
import DB

main = runCGI $ handleErrors cgiMain

cgiMain = do
    request <- getInput "request"
    let req = fromJust request
    let issue_command = "/usr/bin/openssl x509 -CAkey ../ca-key.pem -CA ../ca-cert.pem " ++ " -CAcreateserial " ++ req_or_cert req
    cert      <- liftIO $ run_with_stdin issue_command req
    notbefore <- liftIO $ notBeforeStdin   cert
    notafter  <- liftIO $ notAfterStdin    cert
    fingerp   <- liftIO $ fingerPrintStdin cert
    serial    <- liftIO $ serialStdin      cert
    subj      <- liftIO $ subjectStdin     cert
    let sep = "','"
    liftIO $ db_insert $ "INSERT INTO certificates VALUES ('" ++ subj ++ sep ++ notbefore ++ sep ++ notafter ++ sep ++ cert ++ sep ++ fingerp ++ sep ++ serial ++ sep ++ "CSR" ++ "')"
    setHeader "Content-Type" "text/plain"
    output $ cert

req_or_cert request = if request =~ "^-----BEGIN CERTIFICATE REQUEST-----"
    then "-req"
    else ""
