/*  ARC - Archive utility

    Version 5.21, created on 04/22/87 at 15:05:21

Copyright 1989-90 Lawrence J. Jones; All Rights Reserved
(C) COPYRIGHT 1985-87 by System Enhancement Associates; ALL RIGHTS RESERVED

    By:  Thom Henderson

    Description:
         This program is a general archive utility, and is used to maintain
         an archive of files.  An "archive" is a single file that combines
         many files, reducing storage space and allowing multiple files to
         be handled as one.

    Instructions:
         Run this program with no arguments for complete instructions.

    Programming notes:
         ARC Version 2 differs from version 1 in that archive entries
         are automatically compressed when they are added to the archive,
         making a separate compression step unecessary.  The nature of the
         compression is indicated by the header version number placed in
         each archive entry, as follows:

         0 =          - End of file marker
         1 = Stored   - Old style, no compression (obsolete)
         2 = Stored   - New style, no compression
         3 = Packed   - Repeated character compression
         4 = Squeezed - Huffman encoded after packing (obsolete)
         5 = crunched - 12 bit static LZW (obsolete)
         6 = crunched - 12 bit static LZW after packing (obsolete)
         7 = crunched - 12 bit static LZW after packing with improved
                        hash function
         8 = Crunched - 9 - 12 bit dynamic LZW with adaptive reset
                        after packing
         9 = Squashed - 9 - 13 bit dynamic LZW with adaptive reset
                        (no packing)

         Type 5, Lempel-Ziv packing, was added as of version 4.0

         Type 6 is Lempel-Ziv packing where runs of repeated characters
         have been collapsed, and was added as of version 4.1

         Type 7 is a variation of Lempel-Ziv using a different hash
         function which yields speed improvements of 20-25%, and was
         added as of version 4.6

         Type 8 is a different implementation of Lempel-Ziv, using a
         variable code size and an adaptive block reset, and was added
         as of version 5.0

         Type 9 is yet another version of Lempel-Ziv which uses a variable
         code size and adaptive block reset.  The maximum code size is one
         bit longer which allows better compression.  Also, the file is
         NOT packed first, which makes packing and unpacking faster and
         usually results in better compression as well.  It was first
         used by Phil Katz's PKARC and has been added only to the VMS
         version of ARC.  It is only partially supported.

         Verion 4.3 introduced a temporary file for holding the result
         of the first crunch pass, thus speeding up crunching.

         Version 4.4 introduced the ARCTEMP environment string, so that
         the temporary crunch file may be placed on a ramdisk.  Also
         added was the distinction bewteen Adding a file in all cases,
         and Updating a file only if the disk file is newer than the
         corresponding archive entry.

         The compression method to use is determined when the file is
         added, based on whichever method yields the smallest result.

    Language:
         Computer Innovations Optimizing C86
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "arc.h"

int keepbak = 0;             /* true if saving the old archive */
int warn = 1;                /* true to print warnings */
int note = 1;                /* true to print comments */
int bose = 0;                /* true to be verbose */
int nocomp = 0;              /* true to suppress compression */
int overlay = 0;             /* true to overlay on extract */
int kludge = 0;              /* kludge flag */
int image = 0;               /* image mode requested */
char *arctemp = NULL;        /* arc temp file prefix */
char *password = NULL;       /* encryption password pointer */
int nerrs = 0;               /* number of errors encountered */
int changing = 0;            /* true if archive being modified */

int hdrver;                 /* header version */

FILE *arc;                   /* the old archive */
FILE *new;                   /* the new archive */
char arcname[STRLEN];        /* storage for archive name */
char bakname[STRLEN];        /* storage for backup copy name */
char newname[STRLEN];        /* storage for new archive name */
unsigned short arcdate = 0;  /* archive date stamp */
unsigned short arctime = 0;  /* archive time stamp */
unsigned short olddate = 0;  /* old archive date stamp */
unsigned short oldtime = 0;  /* old archive time stamp */

static char **lst;                     /* files list */
static int lnum;                       /* length of files list */

static void expandlst PROTO((int));


int main(num,arg)                      /* system entry point */
int num;                               /* number of arguments */
char *arg[];                           /* pointers to arguments */
{
    int opt = 0;                       /* selected action */
    char *a;                           /* option pointer */
    int n;                             /* argument index */

    if (num < 3)
    {
    puts("PARC - Portable Archive utility based on SEA's ARC Version 5.21");
    puts("      Version 1.1.3 Beta, created xx:xx xx/xx/xx");
    puts(SYSVER);
    puts("\nCopyright 1989-90 Lawrence J. Jones; All Rights Reserved");
    puts("(C) COPYRIGHT 1985,86,87 by System Enhancement Associates;");
    puts(" ALL RIGHTS RESERVED\n");
    puts("Please refer inquiries about the portable version to:\n");
    puts("       Lawrence J. Jones (scjones@sdrc.com)");
    puts("       701 Woodgate Road, Cincinnati, OH 45244\n");
    puts("Please refer other inquiries to:\n");
    puts("       System Enhancement Associates, Inc.");
    puts("       925 Clifton Ave., Clifton, NJ 07013\n");
    puts("You may copy and distribute this program freely, provided that:");
    puts("    1)   No fee is charged for such copying and distribution, and");
    puts("    2)   It is distributed ONLY in its original,  unmodified state.\n");
    puts("Usage: PARC {amufdxerplvtc}[bswno][i[<n>]][g<password>] <archive> [<file>...]");
    puts("Where:   a   = add files to archive");
    puts("         m   = move files to archive");
    puts("         u   = update files in archive");
    puts("         f   = freshen files in archive");
    puts("         d   = delete files from archive");
    puts("         x,e = extract files from archive");
    puts("         r   = run files from archive");
    puts("         p   = copy files from archive to standard output");
    puts("         l   = list files in archive");
    puts("         v   = verbose listing of files in archive");
    puts("         t   = test archive integrity");
    puts("         c   = convert entry to new packing method");
    puts("         b   = retain backup copy of archive");
    puts("         s   = suppress compression (store only)");
    puts("         w   = suppress warning messages");
    puts("         n   = suppress notes and comments");
    puts("         o   = overwrite existing files when extracting");
    puts("         i   = store/extract in image mode");
    puts("         g   = Encrypt/decrypt archive entry");
    puts("@file can be used to read a list of files from another file\n");
    puts("Please refer to the program documentation for complete instructions.");
    exit(EXIT_FAILURE);
    }

    /* create archive names, supplying defaults */

    makefnam(arg[2], DEFARCNAM, arcname);
    makefnam(DEFWRKNAM, arcname, newname);
    makefnam(DEFBAKNAM, arcname, bakname);

    /* now scan the command and see what we are to do */

    for (a = arg[1]; *a; a++)             /* scan the option flags */
    {    if (strchr("AMUFDXEPLVTCR", toupper(*a))) /* if a known command */
         {    if (opt)                  /* do we have one yet? */
                   fatal("Cannot mix %c and %c", opt, *a);
              opt = toupper(*a);                /* else remember it */
         }
         else switch(toupper(*a))
         {
         case 'B':              /* retain backup copy */
              keepbak = 1;
              break;
         case 'W':              /* suppress warnings */
              warn = 0;
              break;
         case 'N':              /* suppress notes and comments */
              note = 0;
              break;
         case 'O':              /* overwrite file on extract */
              overlay = 1;
              break;
         case 'I':              /* image mode requested */
              image = isdigit(a[1]) ? *++a - '0' : 1;
              break;
         case 'G':              /* garble */
              password = a + 1;
              a += strlen(password);
              break;
         case 'S':              /* storage kludge */
              nocomp = 1;
              break;
         case 'K':              /* special kludge */
              kludge = 1;
              break;
         case '-':
         case '/':   /* UNIX and PC-DOS option markers */
              break;
         default:
              fatal("%c is an unknown command",*a);
         }
    }

    if(!opt)
         fatal("I have nothing to do!");

    /* get the files list set up */

    lnum = num-3;                      /* initial length of list */
    lst = (char **)malloc(lnum > 0 ? lnum * sizeof *lst : sizeof *lst);
    for(n=3; n<num; n++)
         lst[n-3] = arg[n];

    for(n=0; n<lnum; )                 /* expand indirect references */
    {    if(*lst[n] == '@')
              expandlst(n);
         else n++;
    }

    /* act on whatever action command was given */

    switch(opt)                        /* action depends on command */
    {
    case 'A':                          /* Add */
    case 'M':                          /* Move */
    case 'U':                          /* Update */
    case 'F':                          /* Freshen */
         addarc(lnum,lst,(opt=='M'),(opt=='U'),(opt=='F'));
         break;

    case 'D':                          /* Delete */
         delarc(lnum,lst);
         break;

    case 'E':                          /* Extract */
    case 'X':                          /* eXtract */
    case 'P':                          /* Print */
         extarc(lnum,lst,(opt=='P'));
         break;

    case 'V':                          /* Verbose list */
         bose = 1;
    case 'L':                          /* List */
         lstarc(lnum,lst);
         break;

    case 'T':                          /* Test */
         tstarc();
         break;

    case 'C':                          /* Convert */
         cvtarc(lnum,lst);
         break;

    case 'R':                          /* Run */
         runarc(lnum,lst);
         break;

    default:
         fatal("I don't know how to do %c yet!",opt);
    }

    exit(nerrs > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
    /* NOTREACHED */
}

static void expandlst(n)               /* expand an indirect reference */
int n;                                 /* number of entry to expand */
{
    FILE *lf;                          /* list file */
    char buf[100];                     /* input buffer */
    int x;                             /* index */
    char *p = lst[n]+1;                /* filename pointer */

    if(*p)                             /* use name if one was given */
    {    makefnam(p,".cmd",buf);
         if(!(lf=fopen(buf,"r")))
              fatal("Cannot read list of files in %s",buf);
    }
    else lf = stdin;                   /* else use standard input */

    for(x=n+1; x<lnum; x++)            /* drop reference from the list */
         lst[x-1] = lst[x];
    lnum--;

    while(fscanf(lf,"%99s",buf)>0)     /* read in the list */
    {    if (!(lst = (char **)realloc((char *)lst, (lnum + 1) *
                   sizeof (char *))))
              fatal("too many file references");

         lst[lnum] = malloc(strlen(buf)+1);
         strcpy(lst[lnum],buf);        /* save the name */
         lnum++;
    }

    if(lf!=stdin)                      /* avoid closing standard input */
         fclose(lf);
}
