/* gccPj001_6.c */
/* = Kdo.c + gccPj001_5.c  */
/* All messages on "gccPj001.c" are taken out, for import, after    */ 
/*  import, put them back, if it sounds better.                     */

/*  (2005-03-29)  Now, I am getting into Kdo_0[1-5].c codes.   
 *  The file pointer "Stream" is local within OpenAnyFile 
 *  subroutine, and it is renamed in main.c as the file pointer "file".
 *
 *  It was originally, 
 *   main (int argc, char **argv){
 *       file = OpenAnyFile (agrv[1]);
 *   }
 *  to take the argv[1] as the user's input file name.   I only 
 *  need to get the user's fixed filename "HEADER.TXT" or 
 *  "header.txt" so on, thus, it becomes here, 
 *       file = OpenAnyFile ("Header.Txt");
 *  And this works well. 
 */
/*  (2005-03-30)  I finished the rearragement of Kdo codes, 
 *  main(), and two Subroutines OpenAnyFile() and strupr(),
 *  so it is the time to import the whole gccpj001.c into the 
 *  main().
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>

char line [256];
char uType [16];
char lineSDW [256], lineZIP [256];
char lineSDWEr [256], lineZIPEr [256], lineDIFF [256];
/* Those above lines could be all 'line', but they are Global, so 
 *    I took an extra cautious step to avoid any mixed-up.
 */
char folderName [128];


FILE *OpenAnyFile (char *FileName);   /* Kdo's Subroutine */
void *strupr (void *buffer);          /* Kdo's supplemental Subroutine */
extern char *spacedwd (char *to, char *from);
/* = spaced words, to capture blank-containing foldername             */
/* Now is not OSX_Macintosh, so people won't type blank in a filename */
/* but I just leave as it was.                                        */

main ()
{

  char str1[64], str2[64], str3[64];
//  FILE *file;
    FILE *infpSDW, *infpZIP, *outfp1;  
        /* These Pointers read fileNames list */

    outfp1=fopen("Batch.txt", "w");    
        /* outfp1 is for generic output Batch file. */


//  file = OpenAnyFile ("header.txt");  
  infpSDW = OpenAnyFile ("header.txt");
  if (infpSDW)
     printf ("\nReading Header.txt...\n");
  else{
//     perror ("Open failed");
       printf("!!!!!   Please put a \"Header.txt\" file about your Folder\n");
       printf("!!!!!   information.  Please refer to \"Intro.PDF\" about \n");
       printf("!!!!!   how to make it.   And do this again.\n\n");
       exit (0);
  }
/*****    This Block is out of place But COPY CAME UP HERE, ******/ 
/*****    for early notice                                  ******/
/*****    of MISSING "Header.txt" file.                     ******/
/*****************************************************************/


/*  ************ HERE COMES IMPORT << gccpj001.c *************** */
/*  ***** main()'s codes' basic structure above is Kdo's ******* */
// main()
// {
    


  printf("\n\nThis UNIX_Linux Dual_Way is assuming that you have your \n");
  printf("home account, and you made a working folder for this \n");
  printf("Dual_Way there, and are running from there.\n\n  ");


/*  Read user's input from the standard input */
/*  The following User's Magic Variable Inputs work pretty well */
   printf("\nType Your Working Folder name of this Dual-Way, \n");
   printf("     including any upper path (folder name), if exists. \n");
   printf("     For example, suppose you made a working folder called \n");
   printf("     \"DualWay\" directly under your home, then type, \n");
   printf("     For example:  DualWay    :  ");
   scanf("%s", &str1);
   printf("Your Working Folder is set to :  %s\n\n\n\n", str1);
 
   printf("Type Your disk's mounting path (ZIP, Floppy, Jaz, CD, DVD),\n");
   printf("     and any folder name(s) between mounting path and the \n");
   printf("     scanning folders, if exists.  The disk name \"ZIP\" is \n");
   printf("     used just as a representative of removable disk all  \n");
   printf("     the way below, but you can apply other disks. \n");
   printf("For example, if your scanning folders are directly under \n");
   printf("     the floppy disk, and the disk's mounting place is \n");
   printf("     \"/mnt/floppy\".  Then, \n");
   printf("     Type :  /mnt/floppy  \n");
   printf("For example, at the same mounting place, if your floppy  \n");
   printf("     disk's scanning folders are, for example, 16 of Samba \n");
   printf("     Schools names (Aguia_de_Ouro, Mocidade_Alegre, ..)  \n");
   printf("     and they are buried under Geographic partition folders \n");
   printf("     such as, \n");
   printf("     /Brasil/Rio_de_Janeiro/. \n");
   printf("     Then type :  /mnt/floppy/Brasil/Rio_de_Janeiro \n");
   printf("     Type now, from mounting place    :  ");
   scanf("%s", &str3);
   printf("Your disk\'s scanning path is set to   :  %s\n\n", str3);      

   printf("Type Your Shadow (or Mirror) location of Dual Copy \n");
   printf("     on your hard disk, including any sub-folder, if \n");
   printf("     exists, between your HOME and scanning folders, likewise \n");
   printf("     the disk\'s Path typing. \n");
   printf("     For example:  SDW/Brasil/Rio_de_Janeiro    :  \n");
   printf("     Type now, beginning below HOME     :  ");
   scanf("%s", &str2);
   printf("Your Shadow on the hard disk is set to  :  %s\n\n", str2);      

/* Finished user's input.  Now, get started an output. */

    fprintf (outfp1, "#! /bin/tcsh\n");
    fprintf (outfp1, "#! /bin/bash\n\n");

    fprintf (outfp1, "mkdir SDW\n");
    fprintf (outfp1, "mkdir SDW/Erased\n");
    fprintf (outfp1, "mkdir ZIP\n");
    fprintf (outfp1, "mkdir ZIP/Erased\n");
    fprintf (outfp1, "mkdir DIFF\n\n");

   

/*  Read all foldernames listing in "HEADER" file */
/*  First SDW */
/* infpSDW reads All Foldernames at 'HEADER'. */

/* I added, if( infp=fopen() != NULL ) in case an user forgets the "Header" 
 *   file.  Since I myself forget it often, I am making sure that the file
 *   is provided.   I wanted to put this message all the way first, so 
 *   this went up.  Also, in OSX File Association with application became
 *   blur by mixing of Extention and Signature Stamp mechanisms.   So I 
 *   added "Header" and "Header.txt" both works.
 */
 
/********  Here is the ORIGINAL LOCATION of the notice      **********/
/********    about  MISSING "Header  OR  Header.txt" file.   *********/
//     if      (  (infpSDW=fopen("Header",     "r"))!= NULL)      ; 
//    else if (  (infpSDW=fopen("Header.Txt", "r"))!= NULL)      ; 
//    else{
//       printf("!!!!!   Please put a \"Header\" file about your Folder information.\n");
//       printf("!!!!!   And do this again.\n");
//       exit (0);
//    }
//       infpSDW=fopen("Header", "r");

      /*=====  SDW-Catalog  =====*/
	while( (fgets(lineSDW, 64, infpSDW))!=NULL )
	{
	    spacedwd (folderName, &lineSDW[0]);    /* Opening foldername, one-by-one */
        fprintf (outfp1, "cd ~/%s/\"%s\"\n", str2, folderName);
        fprintf (outfp1, "ls -lFR > ~/%s/SDW/\"%s.txt\"\n", str1, folderName);
    }   /* closing While-loop */
    fclose (infpSDW);
    *folderName=0;  /* Reset, in case */
    fprintf (outfp1, "\n");   /* One Spacer line to see SWD, ZIP command lines clearly */
    

/*  Second ZIP */
//    if      (  (infpZIP=fopen("Header",     "r"))!= NULL)      ; 
//    else if (  (infpZIP=fopen("Header.Txt", "r"))!= NULL)      ; 
//    else exit (0);

    /* Reading Header.txt, second time is silent. */
    infpZIP = OpenAnyFile ("header.txt");
    if (infpZIP)
        printf ("     \n");
    else exit (0);



      /*=====  ZIP-Catalog  =====*/
	while( (fgets(lineZIP, 64, infpZIP))!=NULL )
	{
	    spacedwd (folderName, &lineZIP[0]);    /* Opening foldername, one-by-one */
        fprintf (outfp1, "cd %s/\"%s\"\n", str3, folderName);
        fprintf (outfp1, "ls -lFR > ~/%s/ZIP/\"%s.txt\"\n", str1, folderName);
    }   /* closing While-loop */
    fclose (infpZIP);
    *folderName=0;  /* Reset, in case */


/* This message is moved down, because it prompts to look at Batch file which 
 *    is empty, if this message is up before while-loop.
 */
    printf("\n\n\nPlease examine \"Batch.txt\" file in this working folder after you \n");
    printf("will finish this \"1Bat\".  You will see something like below. \n\n");
    printf("#! /bin/tcsh \n");
    printf("#! /bin/bash \n\n");
    printf("mkdir SDW\n");
    printf("mkdir SDW/Erased \n\n");
    printf("cd ~/SDW/Escolas_de_Samba/\"Aguia_de_Ouro\" \n");
    printf("ls -lFR > ~/Way/SDW/\"Aguia_de_Ouro\" \n");  
    printf("cd ~/SDW/Escolas_de_Samba/\"Mocidade_Alegre\" \n");
    printf("ls -lFR > ~/Way/SDW/\"Mocidade_Alegre\" \n\n");
    printf("If you see these lines, we are ready to run this Batch script file.  \n");
    printf("Please read carefully how to run this UNIX/Linux/MacOSX generic \n");
    printf("Batch Shell scripts at \"Unix_Linux_MacOSX.PDF\".  -> \"How to set  \n");
    printf("\'Batch.txt\' as an executable file.\" \n\n\n");
	printf("Type any key then [return] to read through this note :  ");
	scanf( "%s", &uType);


    printf("\n\n\nIf your Batch file is messy, a likely problem is that \n");
    printf("\"Header.txt\" file, so read carefully about trouble shooting \n");
    printf("about \"Header.txt\" file at the trouble shooting in \n");
    printf("\"Unix_Linux_MacOSX.PDF\". \n");
    printf("If your Batch file has the wrong Path, or missing \n");
    printf("parental Path etc., you can run this \"1Bat\" again, OR \n");
    printf("edit the \'Batch.txt\' by your favorite Unix_Linux Editor. \n");
    printf("\"Replace ALL\" works conveniently to fix the Paths. \n\n");
    printf("By a brief test, you may need to Re-new the Executable \n");
    printf("Path before running the Batch file. \n");
    printf("Don\'t forget to change the Batch file permission from \n");
    printf("Read only mode to Read and Executable mode, such as \'chmod 777\'. \n\n");

/* This message is about right time, but until running the Batch file, 
 *    I can't say 
 *    "Please check whether folders are made".
 */
    printf("When you will successfully run the Batch script, you should be able \n");
    printf("to see \"SDW\", \"ZIP\", \"DIFF\" folders in this working folder. \n");
    printf("And those two folders (\"SDW\", \"ZIP\") are filled with catalogs, \n");
    printf("which have all content information of each scanning folder. \n");
    printf("If you will see them, then we can go to the final easy two steps. \n\n\n");
    printf("END of \"1Bat\" \n\n");

    fclose (outfp1);
}
/*  ************* HERE ENDS IMPORT **************** */




/* Here are two SUBROUTINEs by Kdo. */
/* ******************************** */

// FILE *OpenAnyFile (char *FileName);
// void *strupr (void *buffer);   

/* Find any file with same spelling regardless of capitalization */
/* Return a stream to the file, opened for read access           */

FILE *OpenAnyFile (char *FileName) 
{
  DIR *Dir;
  struct dirent *DirEnt;
  char *Target;
  char *Temp;
  FILE *Stream = NULL;

  Target = strdup (FileName);   // make an upper case version of the name.
  strupr (Target);

   Dir = opendir (".");  /* any suitable directory name  */

  while (DirEnt = readdir (Dir))
  {
    Temp = strdup (DirEnt->d_name);
    strupr (Temp); // convert the found name to upper case
    if (strcmp (Temp, Target) == 0)  // names match
    {
      Stream = fopen (DirEnt->d_name, "r");   // open the file for read

      free (Temp);
      break;
    }
    free (Temp);
  }
  free (Target);
  closedir (Dir);
  return (Stream);
}


/*  strupr() isn't universal.  You can make one very easily. */
/*  Pass void so you can pass either char or unsigned char  */
/*    void *strupr (void *buffer);    */  


void *strupr (void *Buffer)
{
  unsigned char *ptr;

  ptr = (unsigned char *)Buffer;
  while (*ptr)
  {
    if (*ptr >= 'a' && *ptr <= 'z')
      *(ptr++) = (*ptr) - 'a' + 'A';
    else
      ptr++;
  }
  return (Buffer);
}