#include "globals.h"
#include "../fileio/fileglob.h"

unsigned long get4();
unsigned short get2();
void pit();
void sit();
void cpt();
void macbinary();

int main(argc, argv)
int argc;
char *argv[];
{
    int c;
    extern int optind;
    extern char *optarg;
    int errflg;

    mode = MACB;
    errflg = 0;

    while((c = getopt(argc, argv, "3adfilqruv")) != EOF) {
	switch(c) {
	case 'r':
	    mode = RSRC;
	    break;
	case 'd':
	    mode = DATA;
	    break;
	case 'u':
	    mode = TEXT;
	    break;
	case 'f':
	    mode = FORK;
	    break;
	case '3':
	    mode = FULL;
	    break;
	case 'a':
#ifdef AUFS_SUPPORT
	    check_aufs();
	    mode = AUFS;
	    break;
#else /* AUFS_SUPPORT */
	    fprintf(stderr, "Sorry, AUFS is not supported.  Recompile or ");
	    fprintf(stderr, "omit -a option.\n");
	    exit(1);
#endif /* AUFS_SUPPORT */
	case 'l':
	    list++;
	    break;
	case 'q':
	    query++;
	    break;
	case 'v':
	    verbose++;
	    break;
	case 'i':
	    info_only++;
	    break;
	case '?':
	    errflg++;
	    break;
	}
    }
    if(errflg) {
	usage();
	exit(1);
    }

    if(optind == argc) {
	infp = stdin;
    } else {
	if((infp = fopen(argv[optind], "r")) == NULL) {
	    fprintf(stderr,"Can't open input file \"%s\"\n",argv[optind]);
	    exit(1);
	}
    }

    if(info_only || verbose || query) {
	list++;
    }
    c = getc(infp);
    (void) ungetc(c, infp);
    switch(c) {
    case 0:
	if(verbose) {
	    printf("This is a file in \"MacBinary\" format.\n");
	}
	macbinary();
	break;
    case 'P':
	if(verbose) {
	    printf("This is a \"PackIt\" archive.\n");
	}
	pit();
	break;
    case 'S':
	if(verbose) {
	    printf("This is a \"StuffIt\" archive.\n");
	}
	sit();
	break;
    case 1:
	if(verbose) {
	    printf("This is a \"Compactor\" archive.\n");
	}
	cpt();
	break;
    default:
	fprintf(stderr, "Unrecognized archive type\n");
	exit(1);
    }
    exit(0);
}

usage()
{
    fprintf(stderr, "Usage: unpack [-irdulvq] filename\n");
}

