/****************************************************************************
*
*                            Open Watcom Project
*
*    Portions Copyright (c) 1983-2002 Sybase, Inc. All Rights Reserved.
*
*  ========================================================================
*
*    This file contains Original Code and/or Modifications of Original
*    Code as defined in and that are subject to the Sybase Open Watcom
*    Public License version 1.0 (the 'License'). You may not use this file
*    except in compliance with the License. BY USING THIS FILE YOU AGREE TO
*    ALL TERMS AND CONDITIONS OF THE LICENSE. A copy of the License is
*    provided with the Original Code and Modifications, and is also
*    available at www.sybase.com/developer/opensource.
*
*    The Original Code and all software distributed under the License are
*    distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
*    EXPRESS OR IMPLIED, AND SYBASE AND ALL CONTRIBUTORS HEREBY DISCLAIM
*    ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF
*    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR
*    NON-INFRINGEMENT. Please see the License for the specific language
*    governing rights and limitations under the License.
*
*  ========================================================================
*
* Description:  WHEN YOU FIGURE OUT WHAT THIS FILE DOES, PLEASE
*               DESCRIBE IT HERE!
*
****************************************************************************/


/************************************************************
*   Copies files from a source directory to the target in which their
*   class files are found. (Sets read-only so that accidental
*   modification of wrong file is impossible.)
*************************************************************/
#define MAX_LINE_LEN 512
#define BUFFER_SIZE 1024
#define JAVA_SUFFIX ".java"
#define CLASS_SUFFIX ".class"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/utime.h>
#include <io.h>
const char *Marker = "/*This file generated by ZSDCopy on %s. DO NOT EDIT!*/";

enum Behavior {COPY, CLEAR};

void SetSlashes(char *buffer, char setTo)
{
    int i;
    for(i=0; i < strlen(buffer); i++)
    {
        if((buffer[i] == '/' ) || (buffer[i] == '\\'))
        {
            buffer[i]=setTo;
        }
        if(buffer[i] == '\n' )
        {
            buffer[i] = '\0';
        }
    }
}

void ClearFile(const char *filename)
{
    char Buf[MAX_LINE_LEN];

    // set file access:
    chmod(filename,S_IRWXU | S_IRWXG | S_IRWXO);

    // clear the file.
    sprintf(Buf,"del /q %s",filename);
    system(Buf);

    printf("cleared file %s\n",filename);
}

void CopyFile(const char *source, const char *dest)
{
    char Buffer[BUFFER_SIZE];
    int numBytes=BUFFER_SIZE+1;
    struct stat fileInfo;
    time_t fileTime;
    struct utimbuf times;
    FILE *in;
    FILE *out;


    time_t time_of_day;
    char buf[26];
    time_of_day = time( NULL );
    _ctime( &time_of_day, buf );
    buf[24]= '\0';


    // see if file is already present.
    if( access( dest, F_OK ) == 0 ) {
        printf("Found existing copy of %s\n",dest);
        ClearFile(dest);
    }



    printf("Copying file: %s.\n to %s.\n",source, dest);

    in = fopen(source,"rt");
    out = fopen(dest,"wt");

    if((in == NULL) )
    {
        printf("Error opening source file for copying: %s\n",source);
        return;
    }
    if( (out == NULL))
    {
        printf("Error opening destination file for copying: %s\n",dest);
        return;
    }

    // print status message
    fprintf(out,Marker,buf );
    while(numBytes >= BUFFER_SIZE) {
        numBytes = fread(Buffer,1,BUFFER_SIZE,in);
        fwrite(Buffer,1,numBytes,out);
    }
    fclose(in);
    fclose(out);

    // set fake file creation time.
    if(-1 != stat( source, &fileInfo) ) {
        times.actime = fileInfo.st_mtime;
        times.modtime = fileInfo.st_mtime;
        utime( dest, &times);
    }



    // set file access:
    chmod(dest,S_IRUSR | S_IRGRP | S_IROTH);

}

void ProcessFilenames(char *source, char *dest)
{
    char drive[ _MAX_DRIVE ];
    char dir[ _MAX_DIR ];
    char fname[ _MAX_FNAME ];
    char ext[ _MAX_EXT ];

    // set slashes correctly and remove initial 'type' indicator.
    SetSlashes(source, '\\' );
    SetSlashes(dest, '\\' );

    // add ".java" to source:
    strcat(source, JAVA_SUFFIX);

    // construct target filename
    _splitpath( source, NULL, NULL, fname, ext );
    _splitpath( dest, drive, dir, NULL, NULL );
    _makepath( dest, drive,dir,fname, ext);

    //printf("source: %s\n",source);
    //printf("dest  : %s\n",dest);


}

void ProcessWJDFile(const char *wjdfile, int action)
{
    char Buffer[MAX_LINE_LEN]= "\0";
    char Source[MAX_LINE_LEN]= "\0";
    char Target[MAX_LINE_LEN]= "\0";
    int FoundSource = 0;

    FILE *list;
    list = fopen(wjdfile, "rt");
    if(list == NULL) {
        printf("Error: unable to open %s\n",wjdfile);
        return;
    }

    while( !feof(list) ) {
        fgets(Buffer, MAX_LINE_LEN, list);
        if(strnicmp(Buffer,"S", 1) == 0)
        {
            if(FoundSource == 1) {
                printf("Error: unable to find target for %s\n",Source);
                fclose(list);
                return;
            }
            strncpy(Source, &Buffer[2],MAX_LINE_LEN);
            FoundSource = 1;
        } else if(strnicmp(Buffer,"T", 1) == 0) {
            if(FoundSource == 1) {
                // we have a source/target pair.
                strncpy(Target,&Buffer[2],MAX_LINE_LEN);
                ProcessFilenames(Source, Target);

                if(0 == stricmp(Source,Target)) {
                    // it's the same file. Do nothing!
                } else if(action == COPY) {
                    CopyFile(Source, Target);
                } else if(action == CLEAR) {
                    ClearFile(Target);
                }
                FoundSource=0;
            }
        }

    }

}


void main(int argc, char *argv[])
{
    switch(argc) {
        case 2:
            ProcessWJDFile(argv[1],COPY);
            break;
        case 3:
            if( 0 == strnicmp(argv[1],"/c",2) )
                ProcessWJDFile(argv[2],CLEAR);
            break;
        default:
            printf("Usage:  ZSDCopy [/c] <filename>.wjd \n   /c will clear files created by default usage.\n");
            break;
    }


}
