module CertInfo where

import Process
-- for chomp, only
import Session

notBefore certfilename = do
    notbefore <- x509 "startdate" certfilename
    return (tailN 10 notbefore)

notAfter certfilename = do
    notafter <- x509 "enddate" certfilename
    return (tailN 9 notafter)

fingerPrint certfilename = do
    fp <- x509 "fingerprint" certfilename
    return (tailN 17 fp)

serial certfilename = do
    ser <- x509 "serial" certfilename
    return (tailN 7 ser)

-- this is actually the CN only
subject certfilename = do
    subj <- x509 "subject" certfilename
    return (untilSlash $ tailN 13 subj)

notBeforeStdin certdata = do
    notbefore <- x509stdin "startdate" certdata
    return (tailN 10 notbefore)

notAfterStdin certdata = do
    notafter <- x509stdin "enddate" certdata
    return (tailN 9 notafter)

fingerPrintStdin certdata = do
    fp <- x509stdin "fingerprint" certdata
    return (tailN 17 fp)

serialStdin certdata = do
    ser <- x509stdin "serial" certdata
    return (tailN 7 ser)

subjectStdin certdata = do
    subj <- x509stdin "subject" certdata
    return (untilSlash $ tailN 13 subj)

x509 option certfile = do
    result <- run ("openssl x509 -in " ++ certfile ++ " -noout -" ++ option)
    return result

x509stdin option certdata = do
    result <- run_with_stdin ("openssl x509 -noout -" ++ option) certdata
    return $ chomp result

tailN 1 l = tail l
tailN n l = tailN (n-1) (tail l)

untilSlash :: String -> String
untilSlash "" = ""
untilSlash ('/':xs) = ""
untilSlash (x:xs) = x : untilSlash xs
