/* Peek into a user's actions on the bbs.
 * Early version that only provides chat capabilities.
 * (C) 1993, Johan. K. Reinalda, WG7J
 */
#include "global.h"
#ifdef LOOKSESSION
#include "socket.h"
#include "session.h"
#include "mailbox.h"
  
void look_input __ARGS((int unused,void *p1,void *p2));
  
int dolook(int argc, char *argv[],void *p) {
    struct session *sp;
    int s,index;
    char c,*cp;
    struct mbx *m;
  
    /* Check if this comes from console - WG7J*/
    if(Curproc->input != Command->input)
        return 0;
  
    if((sp = newsession(argv[1],LOOK,1)) == NULLSESSION)
        return 1;
  
    /* Find the user ! */
    for(m=Mbox;m;m=m->next)
        if(!stricmp(m->name,argv[1]))
            break;
    if(!m) {
        tprintf("%s not a mailbox user!\n",argv[1]);
        keywait(NULLCHAR,1);
        freesession(sp);
        return 0;
    }
  
    index = sp - Sessions;
    sp->s = sp->input;      /* so that doclose() will work ! */
  
    /* Now we need to redirect the network input
     * from the user's socket to our socket...
     */
    sp->proc1 = newproc("look_in",1024,look_input,0,
    (void *)sp,(void *)m,0);
  
    /* Tell the user we are talking to them... */
    usputs(m->user,"\007*** SYSOP Initiated CHAT...\n");
    usflush(m->user);
  
    /* Send whatever's typed on the terminal */
    while(((c = recvchar(sp->input)) != -1) && (usputc(m->user,(char)c) != -1))
        if(c == '\n')
            usflush(m->user);
  
    /* A 'close' command was given, or user disconnected.
     * Notify the user, kill the receiver input task and wait for a response
     * from the user before freeing the session.
     */
    cp = sockerr(sp->input);
    tprintf("%s session %u", Sestypes[sp->type],index);
    tprintf(" closed: %s\n", cp != NULLCHAR ? cp : "EOF");
    if(sp->proc1 != NULLPROC) {
        /* kill the receive process */
        killproc(sp->proc1);
        sp->proc1 = NULLPROC;
        /* restart the mailbox process */
        usputs(m->user,"*** Back in mailbox\n");
        usflush(m->user);
        resume(m->proc);
    }
    keywait(NULLCHAR,1);
    freesession(sp);
    return 0;
}
  
/* User telnet output task, started by user telnet command */
void
look_input(unused,p1,p2)
int unused;
void *p1;
void *p2;
{
    struct session *sp;
    struct mbx *m;
    int input,output,c;
  
    sp = (struct session *)p1;
    m = (struct mbx *)p2;
  
    /* Process input on the users socket connection */
    suspend(m->proc);
    while((c = recvchar(m->user)) != -1)
        tputc((char)c);
    resume(m->proc);
  
    /* Make sure our parent doesn't try to kill us after we exit */
    sp->proc1 = NULLPROC;
}
  
#endif /* LOOKSESSION */
  
