//************************************************
// Project:    System 2.0.0
// Filename:   filefunc.js
// Date&Time:  05.03.2002 - initial version
//			   04.04.2002 - file mask could be a list separated by semi-colon (;)
// Version:	   1.0
//
// Purpose:    Analog of MS-DOS XCopy command with additional datetime support
// Author:     M.Klygin
//************************************************
//**Start Encode**

//var   WshShell = WScript.CreateObject("Wscript.Shell");
//
//var   dirStart = "c:\\Leo8\\app\\LeoTool";
//
//var fso   = new ActiveXObject("Scripting.FileSystemObject");
//
////var res = GetFolderList(dirStart, true) ;
//
////WScript.Echo("res="+res);
//
//var   dirCreate = "c:\\XXX\\YYY\\DDD";
//CreateFolder(dirCreate, true) ;
//
//
//fso = new ActiveXObject("Scripting.FileSystemObject");
////fso.CopyFile ("c:\\leo7\\app\\coral\\sql\\*.sql", "c:\\xxx\\YYY\XXX\\")
//
//WScript.Quit() ;
//

//************************************************
// Function:    GetFolderList
// Arguments:
//  folderspec  directory name
//  reqursive   true - get subdirectory
//
// Purpose:     returns directory list started from given
//              List items are separated by "\n"
// Version:     1.0    
// Author:      M.Klygin
// History:     05.03.2002  initial version
//************************************************
function GetFolderList(folderspec,  reqursive)
{
    var f,  fc;
    var curdir ;
    var s ;

    var fso = new ActiveXObject("Scripting.FileSystemObject");

    s = "" ;

    // Get first directory
    try
    {
        f = fso.GetFolder(folderspec);
    }
    catch (e)
    {
        if (e != 0)
        {
            WScript.Echo("Error: " + e.number + 
                         "\n" + e.description + 
                         "\n" + folderspec) ;
            return s ;
        }
    }
    s+= f.path ;
    s += "\n";
    if (! reqursive)
    {
        return s;
    }

    // Scan all sub-directories
    fc = new Enumerator(f.SubFolders);
    for (;!fc.atEnd(); fc.moveNext())
    {
        curdir = fc.item();

        //s += curdir.path;
        //s += "\n";
        if (reqursive)
        {
            s+= GetFolderList((curdir.path), reqursive);
        }
   }
   return(s);
}

//************************************************
// Function:     CreateFolder
// Arguments:
//  folderspec   directory name
//
// Purpose:      create folder
// Version:      1.0    
// Author:       M.Klygin
// History:      06.03.2002  initial version
//************************************************
function CreateFolder(folderspec, reqursive)
{
    var rc=1 ;

    if (!reqursive)
    {
        rc = prvCreateFolder(folderspec) ;
        return rc ;
    }

    // split full pathname to parts
    var dir_parts = folderspec.split("\\");
    var i=0 ;
    var dir=dir_parts[i] ;

    for (; i < dir_parts.length && rc == 1; i++, dir+="\\"+dir_parts[i])
    {
        rc = prvCreateFolder(dir) ;
        if (rc != 1)
        {
            return rc
        }
    }
    return rc ;
}

//************************************************
// Function:     prvCreateFolder
// Arguments:
//  folderspec   directory name
//
// Purpose:      "private" create folder
// Version:      1.0    
// Author:       M.Klygin
// History:      06.03.2002  initial version
//************************************************
function prvCreateFolder(folderspec)
{
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var rc = 1 ;

    if ( ! fso.FolderExists(folderspec))
    {
        try
        {
            var f = fso.CreateFolder(folderspec) ;  
            f = null;
        }
        catch (e)
        {
            if (e != 0)
            {
                WScript.Echo("Error: " + e.number + 
                             "\n" + e.description + 
                             "\n" + folderspec) ;
                rc = -1 ;
            }
        }
    }
    fso = null;
    return rc ;
}

//************************************************
// Function:     GetFileList
// Arguments:
//  folderspec   directory name
//  reqursive    true - get subdirectory
//
// Purpose:      Returns file list using given filemask with
//               last modification date inside given time interval
// Version:      1.0    
// Author:       M.Klygin
// History:      05.03.2002  initial version
//************************************************
function GetFileList(folderspec, reqursive, filemask, since, till)
{

    var folders = GetFolderList(folderspec, reqursive) ;

    var arFolders = folders.split("\n") ;
    var s="";

    for (var i=0; i < arFolders.length; i++)
    {
        filelist = prvGetFileList(arFolders[i], filemask, since, till) ;
        if (filelist.length > 0 )
        {
            s+=filelist;
            s+="\n" ;
        }
    }
    return s;   
}

function prvGetFileList(folderspec, filemasklist, since, till)
{
   var fso, f, f1, fc, fl, s;
   var ext;

   fso = new ActiveXObject("Scripting.FileSystemObject");

   // Check if folder exists
   if ( ! fso.FolderExists(folderspec))
   {
       return "";
   }
   // Split filemask
   var a_filemask = filemasklist.split(";");

   // Get folder
   f = fso.GetFolder(folderspec);
   fc = new Enumerator(f.files);
   s = "";
   for (; !fc.atEnd(); fc.moveNext())
   {
      fl =  fc.item() ;
      if (fl.DateLastModified >= since &&
          fl.DateLastModified <= till)
      {
          for (var i=0; i < a_filemask.length; i++)
          {
              if (match(fl.name.toLowerCase(),a_filemask[i].toLowerCase()))
              {
                  s += fl.path ;
                  s +="\n";
				  break;
              }
          }
      } 
   }
   return(s);
}

//************************************************
// Function:    prvReplaceDir
// Arguments:
//  sourceDir   source directory name
//  targetDir   target directory name
//  filename    filename
//
// Purpose:     replace one directory name to another
// Version:     1.0    
// Author:      M.Klygin
// History:     05.03.2002  initial version
//************************************************
function prvReplaceDir(sourceDir, targetDir, filename)
{
    //var res = filename.replace(sourceDir, targetDir)
    var res = filename ;
    var pos = filename.toLowerCase().indexOf(sourceDir.toLowerCase()) ;

    if (pos != -1)
    {
        res = replace(filename, pos, sourceDir.length, targetDir);
    }
    return res;
}

//************************************************
// Function:     GetFileCopyList
// Arguments:
//  filelist
//  sourceDir
//  targetDir
//
// Purpose:      returns file copy list
// Version:      1.0    
// Author:       M.Klygin
// History:      05.03.2002  initial version
//************************************************
function GetFileCopyList(sourceDir, targetDir, filelist)
{
    var arFiles = filelist.split("\n") ;
    var s="";
    var filename;
    var filecopy;

    for (var i=0; i < arFiles.length; i++)
    {
        filename = arFiles[i]
        filecopy = prvReplaceDir(sourceDir, targetDir, filename) ;
        s+=filename + "\t" + filecopy ;
        s+="\n" ;
    }
    return s;
}

//************************************************
// Function:     FileCopyList
// Arguments:
//  filelist
//  overwrite
//  move
//  logfile
//
// Purpose:  
// Version:      1.0    
// Author:       M.Klygin
// History:     05.03.2002  initial version
//************************************************
function FileCopyList(filelist, overwrite, move, logFile)
{
    var arFiles = filelist.split("\n") ;
    var s="";
    var sourceFile;
    var targetFile;

    // defaults arguments
    overwrite = arguments.length >= 2 ? overwrite   : false ;
    move      = arguments.length >= 3 ? move        : false ;
    logFile   = arguments.length >= 4 ? logFile     : "" ;

    writeLog(logFile, fill("-",80)) ;
    writeLog(logFile, formatDate(new Date)) ;
    writeLog(logFile, fill("-",80)) ;

debugger;
    
    for (var i=0, rc=1; i < arFiles.length && rc>=0; i++)
    {
        filepair = arFiles[i]
        var arFilePair = filepair.split("\t") ;
        if (arFilePair.length=2)
        {   
            sourceFile = arFilePair[0];
            targetFile = arFilePair[1];
            var rc = prvCopyFile(sourceFile, targetFile, overwrite, move, logFile) ;
        }
    }
    return rc;
}

//************************************************
// Function:     prvCopyFile
// Arguments:
//  sourceFile
//  targetFile
//
// Purpose:     "private" copy file function
// Version:     1.0    
// Author:      M.Klygin
// History:     06.03.2002  initial version
//************************************************
function prvCopyFile(sourceFile, targetFile, overwrite, move, logFile)
{
    // defaults arguments
    overwrite = arguments.length >= 3 ? overwrite   : false ;
    move      = arguments.length >= 4 ? move        : false ;
    logFile   = arguments.length >= 5 ? logFile     : "" ;

    // check if valid
    if (sourceFile.length==0 || targetFile.length==0)
    {
        return 0;
    }
    // 
    var fso = new ActiveXObject("Scripting.FileSystemObject");

    // adjust source, target
    sourceFile = fso.GetAbsolutePathName(sourceFile) ;
    targetFile = fso.GetAbsolutePathName(targetFile) ;

    // check if source exists
    if (! fso.FileExists(sourceFile))
    {
        writeLog(logFile, "not found "+sourceFile);
        return 0;
    }

    // check if target exists
    if (! overwrite && fso.FileExists(targetFile))
    {
        writeLog(logFile, "skip "+sourceFile);
        return 0;
    }   

    // get target directory
    var targetDir = targetFile.substring(0, targetFile.lastIndexOf("\\"));

    // Create target directory
    var rc = 1 ;
    if (! fso.FolderExists(targetDir))
    {
        rc = CreateFolder(targetDir, true) ;
        if (rc != 1) 
        {
            writeLog(logFile, "folder error "+targetDir);
            return rc ; 
        }
    }

    // Copy file
    fso.CopyFile(sourceFile, targetFile, overwrite)
    if (fso.FileExists(targetFile))
    {
        // delete source (move)
        if (!move)
        {
            writeLog(logFile, "copy ok "+sourceFile+" "+targetFile);
        }
        else
        {
            fso.DeleteFile(sourceFile) ;
            writeLog(logFile, "move ok "+sourceFile+" "+targetFile);
        }
    }
    else
    {
        writeLog(logFile, "copy error "+sourceFile+" "+targetFile);
        return -1;
    }
    return 1;
}

//************************************************
// Function:    writeLog
// Arguments:
//  filename    log filename
//  text        text
//  append      append/overwrite flag
//
// Purpose:     write text to log file
// Version:     1.0    
// Author:      M.Klygin
// History:     06.03.2002  initial version
//************************************************

function writeLog (filename, text, append)
{
    var OPEN_FILE_FOR_APPENDING = 8 ;
    var f ;

    append = arguments.length >=3 ? append : true ;

    if (filename.length=0)
    {
        return 0;
    }

    var fso = new ActiveXObject("Scripting.FileSystemObject");

    if (! append && fso.FileExists(filename))
    {
        fso.DeleteFile(filename) ;
    }

    if (fso.FileExists(filename))
    {
        f = fso.OpenTextFile(filename, OPEN_FILE_FOR_APPENDING) ;
        f.WriteLine(text) ;
        f.Close() ;
    }
    else
    {
        f = fso.CreateTextFile(filename, true) ;
        f.WriteLine(text) ;
        f.Close() ;
    }
}
