/***************************************************************************/
/*                                                                         */
/* AutoEncrypt.spot v1.01 © 1994 by Wim Van Goethem                        */
/* If you have any suggestions or problems with this script then you can   */
/* contact me at:                                                          */
/* FidoNet : 2:292/603.6                                                   */
/* UseNet  : wim@augfl.be                                                  */
/*                                                                         */
/***************************************************************************/

ADDRESS SPOT
OPTIONS RESULTS
TRACE OFF

PGPpath = ""  /* Path were you keep PGP (must end on "/", ":" or be empty) */
CR = '0d'x
DelPGPPASS=0  /* Set this to 1 if PGPPASS has to be deleted when the script exits. */

/* See if 'rexxsupport.library' is already loaded and load it if not.      */
IF ~SHOW(Libraries,'rexxsupport.library') THEN
    IF ~ADDLIB("rexxsupport.library",0,-30,0) THEN
    DO
        TextString="RexxSupport.library not found! Exitting."
        CALL Error
    END

/* Does PGPPASS already exists? If so then we won't delete PGPPASS if DelPGPPASS=1. */
NoDelPGPPASS=0
IF EXISTS('env:PGPPASS') THEN NoDelPGPPASS=1

'lockgui'

/* Load the encryption userlist. This is a list of people were too          */
/* you will only (or never) send encrypted mail.                            */
foo=OPEN('userlist','Mail:Spot.encryption','R')
IF ~foo THEN
DO
    TextString="Unable to open Mail:Spot.encryption. Exiting!"
    CALL Error
END
UselistEntries=0
DO WHILE(~EOF('userlist'))
    UselistEntries=UselistEntries+1
    instring=READLN('userlist')
    IF POS(';',instring)~==0 THEN 
    DO
        User.UselistEntries=COMPRESS(LEFT(instring,POS(';',instring)-1))
    END
    ELSE User.UselistEntries=instring
    IF LEFT(User.UselistEntries,1)==" " | LENGTH(User.UselistEntries)==0 | LEFT(User.UselistEntries,1)==";" THEN UselistEntries=UselistEntries-1
END
foo=CLOSE('userlist')

/* Search for netmail areas.                                                */
'firstarea'                 /* This is always a netmail area.               */
DO FOREVER
    'getareaname'
    area=result
    IF LEFT(area,4)=="NET_" THEN CALL SearchExports
    ELSE
    DO
        foo=DELETE("T:Spot.pgptemp_orig")
        foo=DELETE("T:Spot.tempusers")
        'arealist'
        'firstarea'
        'unlockgui'
        IF (DelPGPPASS & ~NoDelPGPPASS) THEN foo=DELETE('Env:PGPPASS')
        EXIT
    END

    'nextarea'
END

/* Search for netmails which should be exported.                            */
SearchExports:
'messages'
'firstmessage EXPORT'       /* Go to the first msg which has to be exported */
IF ~((rc==2) | (rc==0)) THEN RETURN 0   /* No msg has to be exported in this area. */
EndOfArea=0
DO UNTIL EndOfArea==1  /* Search as long as there are msg's which have to be exported. */
    CALL GetMsgFlags
    IF SUBSTR(MsgFlags,4,1)=="1" THEN /* This msg has to be exported, now we have to see if it has to be encrypted. */
    DO
        CALL EncryptYesNo
        IF result THEN CALL EncryptMsg /* EncryptYesNo returned 1, this msg has to be encrypted. */
    END
    'nextmessage'
    IF rc~==0 THEN /* We have reached the end of this area.                 */
    DO
        EndOfArea=1
        'getareaname'
        SAY "Reached the end of area "||result||"."
    END
END
RETURN 0

/* See if the reciever is in our userlist, if so we know what to do.        */
/* A plus sign (+) in front of the name means encryption on.                */
/* A minus sign (-) in front of the name means encryption off.              */
/* If the name of the reciever isn't in the userlist, then we see if we     */
/* have his key, and if so, we ask the user if he wants the msg encrypted.  */
EncryptYesNo:
EMailAddress=""         /* We yet don't know if this is a usenet msg or a fidonet msg. */
'gettoaddress'
RecieverAddress=result  /* This is the fidonet address of the reciever.     */
'getto'
Reciever=result         /* This is the name of the reciever.                */
'getfromaddress'
SenderAddress=result    /* This is the fidonet address of the msg writer.   */
'getfrom'
Sender=result           /* This is the name of the msg writer.              */
'getsubject'
Subject=result          /* The subject of the msg.                          */
'saveascii TO "T:Spot.pgptemp_orig" OVERWRITE NOHEADER NOKLUDGES' /* Save the actual msgbody. */
IF RC~==0 THEN
DO
    TextString="Error writing 'T:Spot.pgptemp_orig'. Exiting!"
    CALL Error
END
/* Read the first line. If the first 3 chars are 'TO:', then the changes    */
/* are that this is a usenet msg. The 'To:' is neccessary for the gate.     */
foo=OPEN("infile","T:Spot.pgptemp_orig","R")
IF ~foo THEN
DO
    TextString="Unable to open 'T:Spot.pgptemp_orig'. Exiting!"
    foo=CLOSE('infile')
    CALL Error
END
instring=READLN('infile')
IF UPPER(LEFT(instring,3))=="TO:" THEN /* This is a usenet e-mail. */
DO
    EMailAddress=RIGHT(instring,LENGTH(instring)-4) /* Get the e-mail address. */
    KeyIDString=EMailAddress
END
ELSE KeyIDString=RecieverAddress
DO x=1 to 10 /* If there is in the first 10 lines no "-----BEGIN PGP MESSAGE----" then this msg is probable not yet encrypted. */
    IF POS("-----BEGIN PGP MESSAGE-----",instring)>=1 THEN
    DO
        foo=CLOSE('infile')
        RETURN 0
    END
    instring=READLN('infile')
END
foo=CLOSE('infile')
DO x=1 TO UselistEntries /* Let's see if we have an entry in our Spot.encryption list for this reciever. */
    IF POS(UPPER(KeyIDString),UPPER(User.x))~==0 THEN
    DO
        IF LEFT(User.x,1)=="+" THEN
        DO
            SAY "Msg to:'"||KeyIDString||"', subject:'"||Subject||"', encryption=ON."
            RETURN 1
        END
        ELSE
        DO
            SAY "Msg to:'"||KeyIDString||"', subject:'"||Subject||"', encryption=OFF."
            RETURN 0
        END
    END
END
/* Couldn't find KeyIDString in userlist, search in keyring.               */
IF ~EXISTS("T:Spot.tempusers") THEN
DO
    ADDRESS COMMAND PGPpath"PGP -kv +verbose=0 >T:Spot.tempusers"
    IF rc~==0 THEN
    DO
        TextString="Unable to create 'T:Spot.tempusers'. Please check that"||CR||"the script can find PGP and that you have enough memory! Exiting!"
        CALL Error
    END
END
foo=OPEN('tempusers','T:Spot.tempusers','R')
IF ~foo THEN
DO
    TextString="Unable to open 'T:Spot.tempusers'. Exiting!"
    foo=CLOSE('tempusers')
    CALL Error
END
DO UNTIL(EOF('tempusers'))
    instring=READLN('tempusers')
    IF POS(UPPER(KeyIDString),UPPER(instring))~==0 THEN
    DO
        'getsubject'
        Subject=result
        'requestresponse TITLE "PGP encryption script" PROMPT "Would you like to encrypt the msg'||CR||'for '||KeyIDString||' about '||Subject||'?" GADGETS "_Yes|_No" CENTER'
        IF rc==1 THEN
        DO
            foo=CLOSE('tempusers')
            SAY "Msg to:'"||KeyIDString||"', subject:'"||Subject||"', encryption=ON."
            RETURN 1
        END
        ELSE
        DO
            foo=CLOSE('tempusers')
            SAY "Msg to:'"||KeyIDString||"', subject:'"||Subject||"', encryption=OFF."
            RETURN 0
        END
    END
END
foo=CLOSE('tempusers')
SAY "Msg to:'"||KeyIDString||"', subject:'"||Subject||"', encryption=OFF."
RETURN 0

/* Here we prepare the msg for encypting.                                   */
EncryptMsg:
IF ~EXISTS("Env:PGPPASS") THEN
DO
    CALL GetPassWord
    IF ~result THEN
    DO
        TextString="User aborts encryption. Exiting!"
        CALL Error
    END
END
NewSubject="*** Subj: "||Subject
foo=OPEN('outfile',"T:Spot.pgptemp_temp","W")
IF ~foo THEN
DO
    TextString="Unable to open 'T:Spot.pgptemp_temp'. Exiting!"
    CALL Error
END
foo=WRITELN('outfile',NewSubject)
IF foo~==LENGTH(NewSubject)+1 THEN
DO
    TextString="Error writing 'T:Spot.pgptemp_temp'. Exiting!"
    CALL Error
END
foo=CLOSE('outfile')
IF EMailAddress=="" THEN /* The reciever has a FidoNet address.             */
DO
    ADDRESS COMMAND "Join T:Spot.pgptemp_temp T:Spot.pgptemp_orig to T:Spot.pgptemp_plainmsg"
    foo=DELETE("T:Spot.pgptemp_temp")
    foo=DELETE("T:Spot.pgptemp_orig")
    CALL Encrypt
    CALL GetMsgFlags
    IF SUBSTR(MsgFlags,5,1)~=="1" THEN Subject="-- PGP --"
    'write TO "'Reciever'" TOADDR "'RecieverAddress'" FROM "'Sender'" FROMADDR "'SenderAddress'" SUBJECT "'Subject'" FILE T:Spot.msgbody REFLOW=OFF NOEDIT NOGUI NOSIG'
END
IF EMailAddress~=="" THEN /* The reciever has a UseNet address.             */
DO
    /* Get those first 2 lines out of the msg text.                         */
    foo=OPEN('outfile',"T:Spot.pgptemp_temp","A")
    IF ~foo THEN
    DO
        TextString="Unable to open 'T:Spot.pgptemp_temp'. Exiting!"
        CALL Error
    END
    foo=OPEN("infile","T:Spot.pgptemp_orig","R")
    IF ~foo THEN
    DO
        TextString="Unable to open 'T:Spot.pgptemp_orig'. Exiting!"
        CALL Error
    END
    DO x=1 TO 2
        instring=READLN('infile')
    END
    DO UNTIL(EOF('infile'))
        instring=READLN('infile')
        foo=WRITELN('outfile',instring)
        IF foo~==LENGTH(instring)+1 THEN
        DO
            TextString="Error writing 'T:Spot.pgptemp_orig'. Exiting!"
            CALL Error
        END
    END
    foo=CLOSE('outfile')
    foo=CLOSE('infile')
    foo=DELETE("T:Spot.pgptemp_orig")
    ADDRESS COMMAND "Rename T:Spot.pgptemp_temp T:Spot.pgptemp_plainmsg"
    CALL Encrypt
    CALL GetMsgFlags
    IF SUBSTR(MsgFlags,5,1)~=="1" THEN Subject="-- PGP --"
    'write TO "'Reciever'" TOADDR "'RecieverAddress'" EMAILADDR "'EMailAddress'" FROM "'Sender'" FROMADDR "'SenderAddress'" SUBJECT "'Subject'" FILE T:Spot.msgbody REFLOW=OFF NOEDIT NOGUI NOSIG'
END
foo=DELETE("T:Spot.msgbody")
'getmessagenum'
OrigMsg=result
CALL GetMsgFlags
'lastmessage'
'setflags KILLSENT'
IF SUBSTR(MsgFlags,2,1)=="1" THEN 'setflags CRASH'
IF SUBSTR(MsgFlags,5,1)=="1" THEN 'setflags FILEATTACH'
IF SUBSTR(MsgFlags,10,1)=="1" THEN 'setflags HOLD'
'gotomessage "'OrigMsg'"'
'clearflags EXPORT'
IF SUBSTR(MsgFlags,8,1)=="1" THEN
DO
    'deletemessage NOREQ'
    'prevmessage'
END
RETURN 0

GetMsgFlags: PROCEDURE EXPOSE MsgFlags
MsgFlags=""
'getmessageflags'
MsgFlags=REVERSE(OVERLAY(c2b(d2c(result)), '000000000000000000000000', 24-LENGTH(c2b(d2c(result)))+1))
RETURN 0

/* Ask the user his password and save it as an env variable.                */
GetPassWord:
'requeststring TITLE "PGP encryption script" PROMPT "Please give your PGP password." INVISIBLE CENTER'
IF rc==5 THEN RETURN 0
ADDRESS COMMAND 'Setenv PGPPASS "'result'"'
RETURN 1

Encrypt:
check=-1
DO UNTIL check==0 | check==1 /* Repeat until PGP exits normally */
    ADDRESS COMMAND PGPpath'PGP +batchmode -esta T:Spot.pgptemp_plainmsg "'KeyIDString'"'
    check = rc
    IF ~(check==0 | check==1) THEN
    DO
        SELECT
            WHEN check==6 THEN 
            DO
                TextString="Stopped at user request. Exitting..."
                CALL Error
            END
            WHEN check==20 THEN
            DO
                'requestresponse TITLE "PGP error" PROMPT "Bad pass phrase. Do you wish to enter a new one?" GADGETS "_Yes, I want to try again.|_No, Quit." CENTER'
                IF rc~==0 THEN
                DO
                    CALL GetPassWord
                    IF ~result THEN
                    DO
                        TextString="User aborts encryption. Exiting!"
                        CALL Error
                    END
                END
                ELSE
                DO
                    TextString="User aborts encryption. Exiting!"
                    CALL Error
                END
            END
            WHEN check==21 THEN 
            DO
                TextString="Cannot find the public key matching userid '"||KeyIDString||"'."||CR||"Exitting..."
                CALL Error
            END
            OTHERWISE
            DO
                TextString="Error '"||check||"' occured. Exitting..."
                CALL Error
            END
        END
    END
END
ADDRESS COMMAND "Rename T:Spot.pgptemp_plainmsg.asc T:Spot.msgbody"
IF rc~==0 THEN
DO
    TextString="Error renaming 'T:Spot.pgptemp_plainmsg.asc' to 'T:Spot.msgbody'. Exiting!"
    CALL Error
END
foo=DELETE("T:Spot.pgptemp_plainmsg")
RETURN 0


/* A fatal error occured. We have to exit.                                  */
Error:
'requestnotify PROMPT "'TextString'" CENTER'
foo=DELETE("T:Spot.pgptemp_orig")
foo=DELETE("T:Spot.tempusers")
foo=DELETE("T:Spot.pgptemp_plainmsg")
foo=DELETE("T:Spot.pgptemp_temp")
foo=DELETE("T:Spot.pgptemp_msgbody")
foo=DELETE("T:Spot.pgptemp_plainmsg.asc")
'unlockgui'
IF (DelPGPPASS & ~NoDelPGPPASS) THEN foo=DELETE('Env:PGPPASS')
EXIT