/* ============================================================= */
/*  Rob Hamerling's MAXIMUS download file scan and sort utility. */
/*  -> Parameter processing routines for DOWNSORT.               */
/* ============================================================= */

// #define DEBUG_MODE

#define INCL_BASE
#include <os2.h>

#include "downsort.h"

#include <ctype.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/*  Symbolic names of keyword parameters */
#define    K_CMT      0
#define    K_TIT      1
#define    K_FNT      2
#define    K_DAT      3
#define    K_ALL      4
#define    K_NEW      5
#define    K_GBL      6
#define    K_BBS      7
#define    K_FIL      8
#define    K_ORP      9
#define    K_NNN     10
#define    K_PRE     11
#define    K_SUB     12
#define    K_BOT     13
#define    K_NDS     14
#define    K_ODS     15
#define    K_END    255

/* ----------------------------------------- */
/* Process commandline and system parameters */
/* ----------------------------------------- */
void get_parm(k,p)
int  k;                                 // parm count
char *p[];                              // pointer array
{
  USHORT i,j,n;                         // counters
  char   c;                             // option letter

  DosGetCtryInfo(sizeof(struct _COUNTRYINFO),&c_code,&c_info,&i);
                                        // for date format, etc
  sys_date(today);                      // start timestamp

  for (i=1; i<k; ++i) {                 // pre-scan
    if (p[i][0]=='@')                   // config filespec
      strncpy(cfg_path,strupr(&p[i][1]),127); // copy filespec
    else if (p[i][0] == '/' || p[i][0] == '-') { // options
      switch(c = toupper(p[i][1])) {
        case VERBOSE   : oper_mode = VERBOSE;   break;
        case QUIET     : oper_mode = QUIET;     break;
        case HELP      : oper_mode = HELP;      break;
        case QMARK     : oper_mode = HELP;      break;
        }
      }
    }

  if (oper_mode == HELP)
    show_help();                        // help explicitly requested
  else if (oper_mode != QUIET)
    show_welcome();                     // good-morning msg
  else
    printf("%s %d.%d%c by %s . . . ",   // simple opening
           PROGNAME,VERSION,SUBVERS,SUFFIX,AUTHOR);

  read_cfg(cfg_path);                   // process configuration file

  for (i=1; i<k; i++) {                 // all commandline parms
    strupr(p[i]);                       // make string upper case

    if (strcmp(p[i],"BBS") == 0 ||
        strncmp(p[i],"BBS:",4) == 0) {  // BBS-list requested
      lp[P_BBS].priv[0] = SYSOP;        // default: HIDDEN
      if (p[i][3] == ':')
        if (conv_priv(&p[i][4],lp[P_BBS].priv,1) <= 0)   // convert
          oper_mode = HELP;
      }

    else if (strcmp(p[i],"NEW") == 0 ||
             strncmp(p[i],"NEW:",4) == 0) { // NEW-list requested
      lp[P_NEW].priv[0] = SYSOP;        // first/only default: SYSOP
      if (p[i][3] == ':')
        if (conv_priv(&p[i][4],lp[P_NEW].priv,10) <= 0)   // convert to int
          oper_mode = HELP;
      }

    else if (strcmp(p[i],"ALL") == 0 ||
             strncmp(p[i],"ALL:",4) == 0) { // ALL-list requested
      lp[P_ALL].priv[0] = SYSOP;        // first/only default: SYSOP
      if (p[i][3] == ':')
        if (conv_priv(&p[i][4],lp[P_ALL].priv,10) <= 0)   // convert to int
          oper_mode = HELP;
      }

    else if (strcmp(p[i],"GBL") == 0 ||
             strncmp(p[i],"GBL:",4) == 0) { // GBL-list requested
      lp[P_GBL].priv[0] = SYSOP;        // first/only default: SYSOP
      if (p[i][3] == ':')
        if (conv_priv(&p[i][4],lp[3].priv,10) <= 0)   // convert to int
          oper_mode = HELP;
      }

    else if (strcmp(p[i],"FIL") == 0 ||
             strncmp(p[i],"FIL:",4) == 0) { // FILES.BBS to be generated
      lp[P_FIL].priv[0] = SYSOP;              //
      if (p[i][3] == ':') {             // path specified?
        strncpy(filesbbs_path,&p[i][4],79);
        j = strlen(filesbbs_path);
        if (j>0 && filesbbs_path[j-1] != '\\')
          filesbbs_path[j] = '\\';      // add backslash if needed
        }
      }

    else if (p[i][0] == '/' || p[i][0] == '-') { // option flag
      switch(c = toupper(p[i][1])) {
        case TRUNC     : for (j=0; j<P_MAX; ++j)
                           lp[j].wrapflag = TRUNC;
                         break;
        case WRAP      : for (j=0; j<P_MAX; ++j)
                           lp[j].wrapflag = WRAP;
                         break;
        case ALPHA     : for (j=0; j<P_MAX; ++j)
                           lp[j].sortflag = ALPHA;
                         break;
        case TIMESTAMP : for (j=0; j<P_MAX; ++j)
                           lp[j].sortflag = TIMESTAMP;
                         break;
        case QUIET     : oper_mode = QUIET;     break;
        case VERBOSE   : oper_mode = VERBOSE;   break;
        case HELP      : oper_mode = HELP;      break;
        case QMARK     : oper_mode = HELP;      break;
        default        : oper_mode = HELP;      break;
        }
      }

    else if (0 < (n = atoi(p[i])))      // numeric: NEW-list length
      for (j=0; j<P_MAX; ++j)
        lp[j].max_fil = n;              // new value for all

    else if (p[i][0] == '@')            // config filespec
      ;                                 // skip

    else
      printf("\nUnknown Parameter: %-50.50s",p[i]);
    }
  }

/* --------------------------------- */
/* Process privilege parameterstring */
/* --------------------------------- */
int conv_priv(c,p,n)
char   *c;                              // parameter string (uppercase)
int    p[];                             // pointer to privilege array
USHORT n;                               // maximum number of privileges
{
  USHORT i,j,k;                         // counters

  for (i=j=0; i<n && c[i]!='\0' && c[i]!=' '; ++i) {
    if (c[i] == '*')                    // asterisk specified?
      p[j] = SYSOP;                     // system default
    else {
      for (k=0; k<HIDDEN-TWIT+1 &&      // search table
                priv_name[k][0]!=toupper(c[i]); k++);
      p[j] = k + TWIT;                  // store real privilege
      }                                 // endif
    if (p[j]<=HIDDEN)                   // hidden or below?
      ++j;                              // count only valid privs
    }                                   // endfor
  for (i=j; i<n; ++i)                   // remaining priv-values
    p[i] = HIDDEN + 1;                  // undo any previous settings
  return(j);                            // number of valid privs
  }

/* ------------------ */
/* Produce time stamp */
/* ------------------ */
char *sys_date(t)
char t[];                               // output buffer
{
  long  secs_now;                       // relative time value
  char *buf;                            // pointer to time string

  time(&secs_now);                      // get current time
  buf = ctime(&secs_now);               // convert to char string
  strcpy(t,buf);                        // copy string
  t[16] = '\0';                         // undo secs, year and newline
  return(t);                            // pointer to buffer
  }

/* =================================== */
/* Process DOWNSORT Configuration File */
/* =================================== */
void read_cfg(ds_cfg)
char ds_cfg[];
{
  FILE *prm;
  char buf[255];
  char *value;                          // ptr to parameter value
  int  i,j,t;

  if ((prm = fopen(ds_cfg,"r")) == NULL )
    printf(OPEN_FAIL,ds_cfg);

  else {
    printf("\nReading configuration file: %s",cfg_path);

    while (fgets(buf,255,prm)) {        // process a line at a time

      switch(parse_keyword(buf,&value)) {

        case K_CMT:                     // Comment and empty lines
          break;

        case K_TIT:                     // list title (ALL, NEW, GBL)
          for (j=0; j<20 && value[j]!='\0'; j++)
            if (value[j] == '~')        // replace tilde by blank
              value[j] = ' ';
          strncpy(list_title,value,20);
          break;

        case K_PRE:                     // pre-title
          title_line(value,pre_title);
          break;

        case K_SUB:                     // sub-title
          title_line(value,sub_title);
          break;

        case K_BOT:                     // bottom line
          title_line(value,bot_lines);
          break;

        case K_ODS:                     // Orphan Description
          strncpy(ORPHAN,value,45);     // copy file text
          break;

        case K_NDS:                     // Orphan Description
          strncpy(NDS,value,45);        // copy file text
          break;

        case K_FNT:                     // Font for all lists
          t = atoi(value);              // convert to integer
          if (t < FONT0 || t > FONT4)   // range check
            printf("\n!Error: TitleFont out of range");
          else
            for (i=0; i<P_MAX; i++)
              lp[i].tfont = t;           // to all parmlist entries
          break;

        case K_DAT:                     // Area.Dat
          strncpy(areadat_path,strupr(value),80);  // copy file specification
          break;

        case K_NNN:
          if (0 < (t = atoi(value)))    // NEW/BBS-list length
            for (i=0; i<P_MAX; ++i)
              lp[i].max_fil = t;        // new value for all lists
          break;

        case K_ALL:                     // create ALL-list(s)
          list_parm(P_ALL,value,10);
          break;

        case K_BBS:                     // create BBS-list
          list_parm(P_BBS,value,1);
          break;

        case K_GBL:                     // create GBL-list
          list_parm(P_GBL,value,10);
          break;

        case K_NEW:                     // create NEW-list(s)
          list_parm(P_NEW,value,10);
          break;

        case K_ORP:                     // naming of ORP-list
          list_parm(P_ORP,value,1);
          break;

        case K_FIL:                     // create FILES.bbs files
          strupr(value);                // all upper case
          conv_priv(value,lp[P_FIL].priv,1);
          if ((value = next_word(value)) != NULL &&
               strcmp(value,"*") != 0)
            strncpy(filesbbs_path,asciiz(value),80);
          break;

        case K_END:                     // Keyword not found
        default:                        // undefined
          printf("\nUnknown Config Parameter: %-50.50s",buf);
          break;
        }
      }
    }
  }

/* =============================== */
/* Process xxxFileList parameters. */
/* =============================== */
void list_parm(k,v,n)
int  k;                                 // appropriate list-parm index
char *v;                                // parameter string pointer
int  n;                                 // max number of privileges
{
  char *nv;                             // moving string pointer
  int  t;                               // intermediate int value

  strupr(v);                            // whole string uppercase
  conv_priv(v,lp[k].priv,n);            // privilege string
  if ((nv = next_word(v)) != NULL  &&   // 1st expected: filename
       strcmp(nv,"*") != 0)             // not asterisk
    strncpy(lp[k].name,asciiz(nv),8);   // customised filename
  while ((nv = next_word(nv)) != NULL) { // remaining parm(s)
    if (nv[0] == '/' || nv[0] == '-') { // option flag
      switch(nv[1]) {
        case TRUNC     : lp[k].wrapflag = TRUNC;     break;
        case WRAP      : lp[k].wrapflag = WRAP;      break;
        case ALPHA     : lp[k].sortflag = ALPHA;     break;
        case TIMESTAMP : lp[k].sortflag = TIMESTAMP; break;
        case FONT      : t = atoi(nv+2);
                         if (t >= FONT0 && t <= FONT3) // range check
                           lp[k].tfont = t;
                         break;
        default        : break;
        }
      }
    else if (0 < atoi(nv))              // numeric: NEW-list length
      lp[k].max_fil = atoi(nv);
    }
  }

/* ============================ */
/* Process xxxTitle parameters. */
/* ============================ */
void  title_line(v,t)
char *v;                                // parameter string pointer
char *t[];                              // pointer to title ptr array
{
  int i,j;                              // counters

  for (i=0; i<MAXTIT && t[i]!=NULL; ++i);  // search 1st free place
  if (i<MAXTIT) {                       // not too many subtitles?
    t[i] = malloc(strlen(v)+1);         // obtain memory
    if (t[i] == NULL) {
      printf(MSG_MEM,PROGNAME);         // not enough memory
      exit(14);
      }
    else {
      for (j=0; v[j]; j++)              // copy whole line
        if (v[j] == '~')                // tilde
          t[i][j] = ' ';                // translate into blank
        else
          t[i][j] = v[j];               // copy
      t[i][j] = '\0';                   // end of string
      }
    }
  }

/* ===================================== */
/* Find the number of the config options */
/* Returns the keyword symbolic number,  */
/* and pointer to the keyword value.     */
/* ===================================== */
int  parse_keyword(line,value)
char line[];                            // input line config file
char **value;                           // return: ptr to value string
                                        // (NULL) if not found
{
  int i,p;                              // counters

  static struct parse_config {          // Keyword Parameter Spec
       unsigned char id;                // parameter identifier
       unsigned char len;               // keyword length
       char *key;                       // keyword
       } cfg[] = {                      // table of keyword parameters
                                        // NOTE: most significant first!
           {K_ALL, 11, "AllFileList"},
           {K_DAT,  7, "AreaDat"},
           {K_BBS, 11, "BbsFileList"},
           {K_BOT, 10, "BottomLine"},
           {K_FIL, 11, "FilFilePath"},
           {K_GBL, 11, "GblFileList"},
           {K_NNN, 11, "MaxNewFiles"},
           {K_NEW, 11, "NewFileList"},
           {K_NDS, 12, "NotFoundDesc"},
           {K_ORP, 11, "OrpFileList"},
           {K_ODS, 10, "OrphanDesc"},
           {K_PRE,  8, "PreTitle"},
           {K_SUB,  8, "SubTitle"},
           {K_FNT,  9, "TitleFont"},
           {K_TIT,  5, "Title"},
           {K_END,  0, ""},             // end of table: keyw. not found
             };

  *value = NULL;                        // init: default return

  for (i=0; line[i]==' '; ++i);         // skip leading blanks
  line = line+i;                        // new local pointer

  if (line[0] == '%'  ||                // comment
      line[0] == ';'  ||                // comment
      line[0] == '*'  ||                // comment
      line[0] == '\n' ||                // end of line
      line[0] == '\0')                  // end of string
    return(K_CMT);                      // return as comment line

  for (i=0; cfg[i].id < K_END &&         // not end of table
           strnicmp(line,cfg[i].key,cfg[i].len) != 0 ; i++);
  p = cfg[i].id;                        // return value

  *value = next_word(line);             // search value string
  if (*value == NULL)                   // no keyword value
    return(K_CMT);                      // treat as comment

  i = strlen(*value);                   // length of value string
  if ((*value)[i-1] == '\n')            // replace end of line
    (*value)[i-1] = '\0';               // by end of string

  return(p);                            // return the keyword number
  }

