/************************************************************************/
/* Copyright 2014 MBARI							*/
/************************************************************************/
/* Summary  : Platform-specific for porting eKermit to BEDS on Persistor*/
/* Filename : bedskermit.c						*/
/* Author   : Robert Herlien (rah)					*/
/* Project  : Benthic Event Detection System (BEDS)			*/
/* Revision : 1.0							*/
/* Created  : 7/21/2014							*/
/*									    */
/* MBARI provides this documentation and code "as is", with no warranty,    */
/* express or implied, of its quality or consistency. It is provided without*/
/* support and without obligation on the part of the Monterey Bay Aquarium  */
/* Research Institute to assist in its use, correction, modification, or    */
/* enhancement. This information should not be published or distributed to  */
/* third parties without specific written permission from MBARI.            */
/*									    */
/************************************************************************/
/* Modification History:						*/
/* 21jul2014 rah - created						*/
/************************************************************************/

#include <cfxpico.h>		/* Persistor PicoDOS definitions	*/
#include <mbariTypes.h>		/* MBARI type definitions		*/
#include <beds.h>		/* BEDS controller definitions		*/
#include <bedskermit.h>		/* Kermit file transfer definitions	*/
#include <syslog.h>		/* BEDS System logger			*/
#include <file.h>		/* BEDS file I/O definitions		*/
#include <fileUtils.h>		/* BEDS file utilities definitions	*/
#include <modem.h>		/* BEDS acoustic modem software		*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>

#include "platform.h"	/* Platform-specific includes and definitions */
#include "cdefs.h"      /* Data types for all modules */
#include "debug.h"	/* Debugging */
#include "kermit.h"	/* Kermit symbols and data structures */
#include "kermitio.h"	/* Kermit I/O module	*/

static int kermitSend(char **fname);


/****************************************/
/*	External Data			*/
/****************************************/

Extern MBool	zmSetRemote;	/* Use remote commands to set SRegs for ZModem*/

Extern UCHAR o_buf[];                   /* Must be defined in kermitio.c */
Extern UCHAR i_buf[];                   /* Must be defined in kermitio.c */
Extern int errno;


/****************************************/
/*	Module Local Data		*/
/****************************************/

MLocal struct k_data k;                        /* Kermit data structure */
MLocal struct k_response r;                    /* Kermit response structure */

//MLocal int action = A_SEND;			/* Send or Receive */
MLocal int xmode = 0;				/* File-transfer mode */
MLocal int ftype = 1;				/* Global file type 0=text 1=binary*/
MLocal int keep = 0;				/* Keep incompletely received files */
MLocal int db = 0;				/* Debugging */
MLocal int parity = P_PARITY;			/* Parity */
MLocal int remote = 1;				/* 1 = Remote, 0 = Local */
MLocal int errcnt = 0;				/* Error count		*/

#ifdef F_CRC
MLocal int check = 3;				/* Block check */
#else
MLocal int check = 1;
#endif /* F_CRC */

MLocal int errorrate = 0;		/* Simulated error rate */
MLocal int seed = 1234;			/* Random number generator seed */


/************************************************************************/
/* Function    : dsKSend						*/
/* Purpose     : Func sent to dirScan to send file via Kermit		*/
/* Inputs      : dirent ptr (per dirScan)				*/
/* Outputs     : TRUE to continue, FALSE to stop			*/
/************************************************************************/
MLocal MBool dsKSend(struct dirent *de, int *rtnp)
{
    char *name[2];

    name[0] = de->d_name;
    name[1] = NULL;

    if ((de->d_attr & (_A_SUBDIR | _A_VOLID)) == 0)
    {
        printf("Set your terminal program for Kermit receive:  %s\n", name[0]);
	sysLogPrintf("Sending %s via Kermit\n", name[0]);
        k.cancel = 0;
	if ((*rtnp = kermitSend(name)) != SUCCESS)
	    errcnt++;
	sysLogPrintf("%s sent via Kermit, result = %d, k.cancel = %d\n",
                     name[0], *rtnp, (int)k.cancel);
    }

    if (k.cancel)
        *rtnp = ERROR;

    return((*rtnp == SUCCESS) ? TRUE : FALSE); /* If failed or cancelled, stop */

} /*dsKSend() */


/************************************************************************/
/* Function    : kermitSendFiles					*/
/* Purpose     : Send multiple files via ZModem prototcol		*/
/* Inputs      : Name (wildcards supported), transfer mode, error rate, debug*/
/* Outputs     : OK or ERROR						*/
/* Comment     : For default, set xfermode = errRate = dbg = 0	*/
/************************************************************************/
int kermitSendFiles(char *name, int xfermode, int errRate, int dbg)
{
    int	remModem = -1, remS3, remS8, rtn = SUCCESS;

    sysLogPrintf("Starting Kermit send for %s\n", name);

    RTCDelayMicroSeconds(500000);
    if (zmSetRemote && isModemPort() && modemCommandMode())
    {
	if ((remModem = getSReg(14)) >= 0)
	{
	    remS3 = getRemoteSReg(remModem, 3);
	    remS8 = getRemoteSReg(remModem, 8);

	    if ((remS3 >= 0) && (remS3 & 0x80))
		setRemoteSReg(remModem, 3, remS3 & 0x7f);
	    if (remS8 > 10)
		setRemoteSReg(remModem, 8, 10);
	}

	modemOnlineMode();
    }

    xmode = 0;
//    ftype = BINARY;                   // BINARY in kermit.h is 0, but
    ftype = 1;                          // 1 actually denotes binary xfer
    errcnt = 0;
    errorrate = errRate;
    db = dbg;

    if (xfermode == 1) {
	xmode = 1;
//      ftype = BINARY;                   // BINARY in kermit.h is 0, but
        ftype = 1;                        // 1 actually denotes binary xfer
    }
    else if (xfermode == 2) {
	xmode = 1;
//      ftype = TEXT;                     // TEXT in kermit.h is 1, but
        ftype = 0;                        // 0 actually denotes ascii xfer
    }

    dirScan(name, dsKSend, &rtn);

    CIOoflush();

    if (k.cancel)
        sysLog("Kermit cancelled\n");
    else
        sysLogPrintf("Kermit finished, errcnt = %d\n", errcnt);

    if (zmSetRemote && isModemPort() && (remModem >= 0) && 
	((remS3 & 0x80) || (remS8 > 10)))
	if (modemCommandMode())
	{
	    if ((remS3 >= 0) && (remS3 & 0x80))
		setRemoteSReg(remModem, 3, remS3);
	    if (remS8 > 10)
		setRemoteSReg(remModem, 8, remS8);

	    modemOnlineMode();
	}

    return((rtn == SUCCESS) ? OK : ERROR);
}


/*
  Code taken from main.c in ekermit distribution
*/

static int doexit(int status)
{
    sysLogPrintf("Kermit doexit(%d)\n", status);
    devrestore();                       /* Restore device */
    devclose();                         /* Close device */
    if (db)				/* Close debug log */
      debug(DB_CLS,"",0,0);

    return(status);
}


static int kermitSend(char **fname)
{
    int status, rx_len, i, x;
    char c;
    UCHAR *inbuf;
    short r_slot;

    parity = P_PARITY;                  /* Set this to desired parity */
    status = X_OK;                      /* Initial kermit status */

/* THE REAL STUFF IS FROM HERE DOWN */

    if (!devopen("dummy"))		/* Open the communication device */
	return(doexit(FAILURE));
    if (!devsettings("dummy"))		/* Perform any needed settings */
	return(doexit(FAILURE));
    if (db)				/* Open debug log if requested */
      debug(DB_OPN,"kermit.log",0,0);

    debug(DB_MSG,"Initializing...",0,0);

#ifdef DEBUG
    if (errorrate) {
	debug(DB_LOG,"SIMULATED ERROR RATE:",0,errorrate);
	srand(seed);		/* Init random error generator */
	xSetErrRate(errorrate);
    }

#endif /* DEBUG */

/*  Fill in parameters for this run */

    k.xfermode = xmode;			/* Text/binary automatic/manual  */
    k.remote = remote;			/* Remote vs local */
    k.binary = ftype;			/* 0 = text, 1 = binary */
    k.parity = parity;                  /* Communications parity */
    k.bct = check;			/* Block check type */
    k.ikeep = keep;			/* Keep incompletely received files */
    k.filelist = fname;			/* List of files to send (if any) */
    k.filename = fname;			/* Current file to send (if any) */
    k.cancel = 0;			/* Not canceled yet */

/*  Fill in the i/o pointers  */
  
    k.zinbuf = i_buf;			/* File input buffer */
    k.zinlen = IBUFLEN;			/* File input buffer length */
    k.zincnt = 0;			/* File input buffer position */
    k.obuf = o_buf;			/* File output buffer */
    k.obuflen = OBUFLEN;		/* File output buffer length */
    k.obufpos = 0;			/* File output buffer position */

/* Fill in function pointers */

    k.rxd    = readpkt;			/* for reading packets */
    k.txd    = tx_data;			/* for sending packets */
    k.ixd    = inchk;			/* for checking connection */
    k.openf  = openfile;                /* for opening files */
    k.finfo  = fileinfo;                /* for getting file info */
    k.readf  = readfile;		/* for reading files */
    k.writef = writefile;               /* for writing to output file */
    k.closef = closefile;               /* for closing files */
#ifdef DEBUG
    k.dbf    = db ? dodebug : 0;	/* for debugging */
#else
    k.dbf    = 0;
#endif /* DEBUG */

/* Initialize Kermit protocol */

    status = kermit(K_INIT, &k, 0, 0, "", &r);
#ifdef DEBUG
    debug(DB_LOG,"init status:",0,status);
    debug(DB_LOG,"version:",k.version,0);
#endif /* DEBUG */
    if (status == X_ERROR)
	return(doexit(FAILURE));
//    if (action == A_SEND)
    status = kermit(K_SEND, &k, 0, 0, "", &r);
/*
  Now we read a packet ourselves and call Kermit with it.  Normally, Kermit
  would read its own packets, but in the embedded context, the device must be
  free to do other things while waiting for a packet to arrive.  So the real
  control program might dispatch to other types of tasks, of which Kermit is
  only one.  But in order to read a packet into Kermit's internal buffer, we
  have to ask for a buffer address and slot number.

  To interrupt a transfer in progress, set k.cancel to I_FILE to interrupt
  only the current file, or to I_GROUP to cancel the current file and all
  remaining files.  To cancel the whole operation in such a way that the
  both Kermits return an error status, call Kermit with K_ERROR.
*/
    while (status != X_DONE) {
/*
  Here we block waiting for a packet to come in (unless readpkt times out).
  Another possibility would be to call inchk() to see if any bytes are waiting
  to be read, and if not, go do something else for a while, then come back
  here and check again.
*/
        inbuf = getrslot(&k,&r_slot);	/* Allocate a window slot */
        rx_len = k.rxd(&k,inbuf,P_PKTLEN); /* Try to read a packet */
        debug(DB_PKT,"main packet",&(k.ipktbuf[0][r_slot]),rx_len);
/*
  For simplicity, kermit() ACKs the packet immediately after verifying it was
  received correctly.  If, afterwards, the control program fails to handle the
  data correctly (e.g. can't open file, can't write data, can't close file),
  then it tells Kermit to send an Error packet next time through the loop.
*/
        if (rx_len < 1) {               /* No data was read */
            freerslot(&k,r_slot);	/* So free the window slot */
            if (rx_len < 0)             /* If there was a fatal error */
		return(doexit(FAILURE));/* give up */

	    /* This would be another place to dispatch to another task */
	    /* while waiting for a Kermit packet to show up. */

        }
        /* Handle the input */

        switch (status = kermit(K_RUN, &k, r_slot, rx_len, "", &r)) {
	  case X_OK:
#ifdef DEBUG
/*
  This shows how, after each packet, you get the protocol state, file name,
  date, size, and bytes transferred so far.  These can be used in a
  file-transfer progress display, log, etc.
*/
	    debug(DB_LOG,"NAME",r.filename ? (char *)r.filename : "(NULL)",0);
	    debug(DB_LOG,"DATE",r.filedate ? (char *)r.filedate : "(NULL)",0);
	    debug(DB_LOG,"SIZE",0,r.filesize);
	    debug(DB_LOG,"STATE",0,r.status);
	    debug(DB_LOG,"SOFAR",0,r.sofar);
#endif /* DEBUG */
	    /* Maybe do other brief tasks here... */
	    continue;			/* Keep looping */
	  case X_DONE:
	    break;			/* Finished */
	  case X_ERROR:
	      return(doexit(FAILURE));	/* Failed */
	}
    }
    return(doexit(SUCCESS));
}
