#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

static int stepdown(char *root,int tiefe);
static int ndir,nfile;

int main(int argc,char **argv)
{
   int tiefe;
   int i;
   char root[4096];

   if ( argc < 3 )
   {
      fprintf(stderr,"tb_treetest root tiefe\n");
      exit(1);
   }
/*
   create a directory tree starting with <root>. each dir is named by a 
   number giving the amount of dirs/files contained in that dir. each
   file name ends with _f.
*/
   if ( !(tiefe = atoi(argv[2])) )
   {
      exit(0);
   }
   ndir  = 0;
   nfile = 0;
   sprintf(root,"%s",argv[1]);
   if ( mkdir(root,(mode_t)0755) )
   {
      fprintf(stderr,"can't mkdir %s. %d %s\n",root,errno,strerror(errno));
      exit(1);
   }
   for ( i=0; i<tiefe; i++ )
   {
      sprintf(root,"%s/%d",argv[1],i);
      if ( mkdir(root,(mode_t)0755) )
      {
         fprintf(stderr,"can't mkdir %s. %d %s\n",root,errno,strerror(errno));
         exit(1);
      }
      if ( chdir(root) )
      {
         fprintf(stderr,"can't chdir %s. %d %s\n",root,errno,strerror(errno));
         exit(1);
      }
      if ( stepdown(root,i) )
      {
         fprintf(stderr,"can't stepdown\n");
         exit(1);
      }
   }
   fprintf(stdout,"created %d files and %d directories\n",nfile,ndir);
   exit(0);
}

static int stepdown(char *root,int tiefe)
{
   int  i,fd;
   char dir[4096],file[4096];

   if ( !tiefe )
   {
      return(0);
   }
   for ( i=0; i<tiefe; i++ )
   {
      sprintf(dir,"%d",i);
      sprintf(file,"%d_f",i); 
      if ( (fd = creat(file,(mode_t)0755)) < 0 )
      {
         fprintf(stderr,"can't create file %s. %d %s\n",file,errno,
                 strerror(errno));
         return(1);
      }
      close(fd);
      nfile++;
      if ( mkdir(dir,(mode_t)0755) )
      {
         fprintf(stderr,"can't mkdir %s. %d %s\n",dir,errno,strerror(errno));
         return(1);
      }
      ndir++;
      if ( chdir(dir) )
      {
         fprintf(stderr,"can't chdir %s. %d %s\n",root,errno,strerror(errno));
         return(1);
      }
      if ( stepdown(dir,i) )
      {
         fprintf(stderr,"stepdown failed\n");
         return(1);
      }
      if ( chdir("..") )
      {
         fprintf(stderr,"can't step up. %d %s\n",errno,strerror(errno));
         return(1);
      }
   }
   return(0);
}
