#!/usr/bin/env runghc

-- This is a CGI script that allows you to link directly to records in the
-- familysearch.org Ancestral File using the AFN number.

import System.Unix.Process
import Data.ByteString.Lazy.Char8 (empty, unpack)
import Data.List (isPrefixOf, tails, find, lookup)
import Data.Maybe (fromJust)
import Network.CGI
import Network.CGI.Protocol (cgiInputs, inputValue)
import Network.CGI.Monad (cgiGet)

main = runCGI afn

afn :: CGIT IO CGIResult
afn =
    do alist <- (cgiGet cgiInputs)
       let file = inputValue (fromJust (lookup "file_number" alist))
       (out, _err, _code) <- liftIO $ lazyCommand ("curl -s 'http://www.familysearch.org/Eng/Search/customsearchresults.asp?date_range_index=0&type=0&LDS=0&event_index=0&date_range=0&file_number=" ++ unpack file ++ "&standardize=N&submit=Search&clear=Clear'") empty >>= return . collectOutputUnpacked
       let uri = maybe Nothing (Just . takeWhile (/= '"')) (find (isPrefixOf "af/individual_record.asp?recid=") (tails out))
       redirect ("http://www.familysearch.org/Eng/Search/" ++ (fromJust uri))

