/* gccPj001_7.c */
/* = Kdo.c + gccPj001_5.c  */

/*  (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".
 *
 */
/*  (2006-07-27, 2008-03-10)    Three major paths are, 
 *
 *    PATH_1 =  strcpy (DEFAULT_1, "/var/www/html");
 *    PATH_2 =  strcpy (DEFAULT_2, "/var/www/html/htm");
 *    PATH_3 =  strcpy (DEFAULT_3, "/var/www");
 *
 *  For [PATH_1 Catalog], I included /html/htm as a 
 *  special no recursive -R option, otherwise it will include about 
 *  10 [lc] language big sub-directories.   
 */
/*  (2008-03-10)    There are also three Static_directories in the C-codes.
 *  below.   You erase them or customize them.
 *      
 *     /home/mkido/1dual
 *     /home/mkido/admin_link
 *     /home/mkido/bin
 *   
 */
/*  (2008-03-10)    ATTENTION !!!   While compiling this [gccPj001_7.c], 
 *  you need to use the special Switch.    That is about line number 80  
 *  of this file, [ ****  Compiling for SDW or NET   *****].  
 * 
 *  SDW switch makes 1Bat, 2Er, 3Diff for shadow server of silhouette.
 *  NET switch makes 1Bat, 2Er, 3Diff for main server on Internet.
 *
 *  Only the 1Bat is different between shadow server and main server though.
 */



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

char line [256];
char uType [16];
char linePATH_1 [256], linePATH_2 [256], linePATH_3 [256];
char linePATH_1Er [256], linePATH_2Er [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 str0[64], str1[64], str2[64], str3[64];
  char DEFAULT_1[64], DEFAULT_2[64], DEFAULT_3[64];
  char MAGIC_SDW_NET[64];
  char MAGIC_1[64], MAGIC_2[64], MAGIC_3[64];
  char MAGIC_FN1[64], MAGIC_FN2[64], MAGIC_FN3[64];
  int SW1, SW2, SW3;


//  FILE *file;
    FILE *infpPATH_1, *infpPATH_2, *infpPATH_3, *outfp1, *outfp2;  
        /* These Pointers read fileNames list */


  SW1=SW2=SW3 = 0;

// *****  Compiling for SDW or NET  *******
//  strcpy (MAGIC_SDW_NET, "SDW");
  strcpy (MAGIC_SDW_NET, "NET");

//  Directories to scan
  strcpy (DEFAULT_1, "/var/www/html");
  strcpy (DEFAULT_2, "/var/www/html/htm");
  strcpy (DEFAULT_3, "/var/www");

//  Additional static directories
  strcpy (MAGIC_1, "/home/mkido/1dual");
  strcpy (MAGIC_2, "/home/mkido/admin_link");
  strcpy (MAGIC_3, "/home/mkido/bin");
  strcpy (MAGIC_FN1, "1dual");
  strcpy (MAGIC_FN2, "admin_link");
  strcpy (MAGIC_FN3, "bin");






    outfp1=fopen("Batch.txt", "w");    
        /* outfp1 is for generic output Batch file. */
    outfp2=fopen("header.txt", "w");    
        /* outfp2 makes integrated file, header_1.txt + header_2.txt + static_folder_names. */


/*  First PATH_1    ==============================================    */
  infpPATH_1 = OpenAnyFile ("header_1.txt");
  if (infpPATH_1) {
     printf ("\nReading .....  Header_1.txt, Header_2.txt, \n");
     printf ("Header_3.txt, automatically for 3 different PATHs ... \n");
  } else {
//     perror ("Open failed");
       printf("!!!!!   Please put a \"Header_1.txt\", \"Header_2.txt\",     \n");
       printf("!!!!!   \"Header_3.txt\" files about your scanning folders   \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 Linux Server DUAL is modified from local DUAL  \n");
  printf("(ZIP/FLASH <=> Hard disk).  This Linux Server DUAL        \n");
  printf("compares two machines. One Linux Server is running on  \n");
  printf("the Internet, while the other shadow Linux Server      \n");
  printf("(silhouette) stays out of the Internet.  Only when     \n");
  printf("the main Server machine downs, the shadow Linux Server  \n");
  printf("will take place the main server's post.                 \n");
  printf("The 100 percent same content in two machines is desirable.  \n");
  printf("Please customize it which works for you.  This is just  \n");
  printf("good for me now.         \n\n");


/*  Read user's input from the standard input */
/*  The following User's Magic Variable Inputs work pretty well */
   printf("The following asks you three main PATHs of scanning, and       \n");
   printf("automatically appending three static directory without asking. \n");
   printf("They works for me now.   You must customize them for your      \n");
   printf("servers in C-codes level.   Very easy!    \n\n");
   printf("\nType your working folder name in which you runs this DUAL. \n");
   printf("     I usually make \"1dual\" folder at my home.    \n");
   printf("     For example:  1dual    :  ");
   scanf("%s", &str0);
   printf("Your Working Folder is set to :  %s\n\n\n\n", str0);

/* ----------------------------------------------   */
   printf("Default OR another scanning path for PATH_1 ? \n");
   printf("     Please select the switch. \n");
   printf("        1.  Default /var/www/html  for PATH_1. \n");
   printf("        2.  Type different path. \n");
   printf("     Select the switch [1 or 2] : ");
   scanf("%d", &SW1);
   if (SW1==1) { strcpy (str1, DEFAULT_1); }
   else if (SW1==2) {
      printf("     For example:  /home/mkido/Brasil/Rio_de_Janeiro    \n");
      printf("     Type now   :  ");
      scanf("%s", &str1);
   }
   printf("Scanning PATH_1 is set to  :  %s\n\n", str1);      


/* ----------------------------------------------   */ 
   printf("Default OR another scanning path for PATH_2 ? \n");
   printf("     Please select the switch. \n");
   printf("        1.  Default /var/www/html/htm  for PATH_2. \n");
   printf("        2.  Type different path. \n");
   printf("     Select the switch [1 or 2] : ");
   scanf("%d", &SW2);
   if (SW2==1) { strcpy (str2, DEFAULT_2); }
   else if (SW2==2) {
      printf("     For example:  /home/mkido/Brasil/Sao_Paulo    \n");
      printf("     Type now   :  ");
      scanf("%s", &str2);
   }
   printf("Scanning PATH_2 is set to   :  %s\n\n", str2);      


/* ----------------------------------------------   */
   printf("Default OR another scanning path for PATH_3 ? \n");
   printf("     Please select the switch. \n");
   printf("        1.  Default /var/www/   for PATH_3. \n");
   printf("        2.  Type different path. \n");
   printf("     Select the switch [1 or 2] : ");
   scanf("%d", &SW3);
   if (SW3==1) { strcpy (str3, DEFAULT_3); }
   else if (SW3==2) {
      printf("     For example :  /home/mkido/Bolivia/Santa_Cruz_de_la_Sierra   \n");
      printf("     Type now   :  ");
      scanf("%s", &str3);
   }
   printf("Scanning PATH_3 is set to   :  %s\n\n", str3);      

/* ----------------------------------------------   */



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

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

   if( strncmp ("SDW", MAGIC_SDW_NET, 3) == 0 ){
    fprintf (outfp1, "mkdir SDW\n");
    fprintf (outfp1, "mkdir SDW/Erased\n");
    fprintf (outfp1, "mkdir DIFF\n\n");
   }
   if( strncmp ("NET", MAGIC_SDW_NET, 3) == 0 ){
    fprintf (outfp1, "mkdir NET\n");
    fprintf (outfp1, "mkdir NET/Erased\n");
   }

   fprintf (outfp1, "\n");   /* One Spacer line before we get started a catalog command line. */
   

/*  Read all foldernames listing in "HEADER" file */

/* 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.  
 */
 
/********  Here is the ORIGINAL LOCATION of the notice      **********/
/********    about  MISSING "Header  OR  Header.txt" file.   *********/
//     if      (  (infpPATH_1=fopen("Header",     "r"))!= NULL)      ; 
//    else if (  (infpPATH_1=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);
//    }


    /*=====  Making PATH_1 Catalog  =====*/
    while( (fgets(linePATH_1, 64, infpPATH_1))!=NULL )
    {
	spacedwd (folderName, &linePATH_1[0]);    /* Opening foldername, one-by-one */
        fprintf (outfp1, "cd %s/\"%s\"\n", str1, folderName);
        /*  The if-loop below is a special handling, not to have R-RECURSIVE  */
        if( strcmp("htm", folderName)==0 ){
            fprintf (outfp1, "ls -lF > ~/%s/%s/\"%s.txt\"\n", str0, MAGIC_SDW_NET, folderName);
        }else{
            fprintf (outfp1, "ls -lFR > ~/%s/%s/\"%s.txt\"\n", str0, MAGIC_SDW_NET, folderName);
        }
        fprintf (outfp2, "%s\n", folderName);  /* Extra, writing header.txt */
    }   /* closing While-loop */
    fclose (infpPATH_1);
    *folderName=0;  /* Reset, in case */
    fprintf (outfp1, "\n");   /* One Spacer line to see PATH_1, PATH_2 command lines clearly */
    



/*  Second PATH_2    =======================================================     */
    /* Reading Header2.txt. */
    infpPATH_2 = OpenAnyFile ("header_2.txt");
    if (infpPATH_2)
        printf ("     \n");
    else exit (0);

    /*=====  Making PATH_2 Catalog  =====*/
    while( (fgets(linePATH_2, 64, infpPATH_2))!=NULL )
    {
	spacedwd (folderName, &linePATH_2[0]);    /* Opening foldername, one-by-one */
        fprintf (outfp1, "cd %s/\"%s\"\n", str2, folderName);
        fprintf (outfp1, "ls -lFR > ~/%s/%s/\"%s.txt\"\n", str0, MAGIC_SDW_NET, folderName);
        fprintf (outfp2, "%s\n", folderName);  /* Extra, writing header.txt */
    }   /* closing While-loop */
    fclose (infpPATH_2);
    *folderName=0;  /* Reset, in case */
    fprintf (outfp1, "\n");   /* One Spacer line to see PATH_2, PATH_3 command lines clearly */





/*  Second PATH_3   ===============================================================     */
    /* Reading Header3.txt. */
    infpPATH_3 = OpenAnyFile ("header_3.txt");
    if (infpPATH_3)
        printf ("     \n");
    else exit (0);

    /*=====  Making PATH_3 Catalog  =====*/
    while( (fgets(linePATH_3, 64, infpPATH_3))!=NULL )
    {
	spacedwd (folderName, &linePATH_3[0]);    /* Opening foldername, one-by-one */
        fprintf (outfp1, "cd %s/\"%s\"\n", str3, folderName);
        fprintf (outfp1, "ls -lFR > ~/%s/%s/\"%s.txt\"\n", str0, MAGIC_SDW_NET, folderName);
        fprintf (outfp2, "%s\n", folderName);  /* Extra, writing header.txt */
    }   /* closing While-loop */
    fclose (infpPATH_3);
    *folderName=0;  /* Reset, in case */



      /*=====  PATH_MAGIC_STATIC-Catalog  =====*/
        fprintf (outfp1, "\n");

        fprintf (outfp1, "cd %s\n", MAGIC_1);
        fprintf (outfp1, "ls -lFR > ~/%s/%s/%s.txt\n", str0, MAGIC_SDW_NET, MAGIC_FN1);
        fprintf (outfp1, "cd %s\n", MAGIC_2);
        fprintf (outfp1, "ls -lFR > ~/%s/%s/%s.txt\n", str0, MAGIC_SDW_NET, MAGIC_FN2);
        fprintf (outfp1, "cd %s\n", MAGIC_3);
        fprintf (outfp1, "ls -lFR > ~/%s/%s/%s.txt\n", str0, MAGIC_SDW_NET, MAGIC_FN3);

        /*  Extra, writing header.txt */
        fprintf (outfp2, "%s\n", MAGIC_FN1);
        fprintf (outfp2, "%s\n", MAGIC_FN2);
        fprintf (outfp2, "%s\n", MAGIC_FN3);


/* 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");
    printf("mkdir DIFF \n\n");
    printf("cd /var/www/html/Escolas_de_Samba/\"Aguia_de_Ouro\" \n");
    printf("ls -lFR > ~/1dual/SDW/\"Aguia_de_Ouro\" \n");  
    printf("cd /var/www/html/Escolas_de_Samba/\"Mocidade_Alegre\" \n");
    printf("ls -lFR > ~/1dual/SDW/\"Mocidade_Alegre\" \n\n");
    printf("Assuming your computer has all set of Samba schools\' folder name, you   \n");
    printf("would see like 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\" and \"DIFF\" folders at Shadow Linux server, and \"NET\"       \n");
    printf("at Main Linux Server on Internet.   You need to do file transfer (FTP) the     \n");
    printf("entire \"NET\" folder into Shadow server, or file transfer \"SDW\" and          \n");
    printf("\"DIFF\" folders to Main Server on Internet.   It doesn't matter.   We just     \n");
    printf("need a set of 3 folders at one place before running the final two steps.        \n");
    printf("And those two folders (\"SDW\" or \"NET\") 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);
    fclose (outfp2);
}
/*  ************* 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);
}