/*
Copyright (c) 2000-2010, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.
* Redistributions in binary form must reproduce the above 
  opyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials
  provided with the distribution.
* Neither the name of the Dirk Krause nor the names of
  contributors may be used to endorse or promote
  products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/



/**	@file	cona.c	Correct file names.
The purpose of this program is to correct file names.
*/



/*
	cona -test <dir>
	cona <dir>

	COrrect fileNAmes
	cona tries to rename directory entries so they do not
	contain unprintable characters
*/

#include <stdio.h>

#include <dk.h>

#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <dirent.h>

#include <dksf.h>


#line 69 "cona.ctr"


static char oldname[MAXPATHLEN], newname[4*MAXPATHLEN];
static int  in_test_mode = 0;

struct backtrack {
  int state;
  struct backtrack *last;
  char *pathname;
  DIR *dir;
};

typedef struct backtrack BackTrack;

static int backtrack_init(BackTrack *bt)
{
  int back = 0;
  char *ptr; size_t s;
  bt->state = 0;
  bt->last = NULL;
  bt->pathname = NULL;
  bt->dir = NULL;
  
  bt->pathname = malloc(MAXPATHLEN);
  if(bt->pathname) {
    back = 1;
    ptr = bt->pathname; s = MAXPATHLEN;
    while(s--) {
      *(ptr++) = (char)0;
    }
  } 
  return back;
}

static void backtrack_end(BackTrack *bt)
{
  char *x;
  
  if(bt->pathname) {
    x = bt->pathname;
    free(x);
  }
  if(bt->dir) {
    closedir(bt->dir);
  }
  
}

static void backtrack_free(BackTrack *bt)
{
  
  backtrack_end(bt);
  free(bt);
  
}


static BackTrack *backtrack_new(void)
{
  BackTrack *back = NULL;
  
  back = malloc(sizeof(BackTrack));
  if(back) {
    if(!backtrack_init(back)) {
      backtrack_end(back);
      back = NULL;
    }
  } 
  return back;
}

static void create_new_filename(char *filename)
{
  char *ptr1, *ptr2;
  
  ptr1 = filename; ptr2 = newname;
  while(*ptr1) {
    if((*ptr1 == '0') || ((*ptr1 >= '1') && (*ptr1 <= '9'))) {
      *(ptr2++) = *ptr1;
    } else {
      if(((*ptr1 >= 'A') && (*ptr1 <= 'Z')) || (*ptr1 == '-') || (*ptr1 == '+')) {
        *(ptr2++) = *ptr1;
      } else {
        if(((*ptr1 >= 'a') && (*ptr1 <= 'z')) || (*ptr1 == '~') || (*ptr1 == '$') || (*ptr1 == '!') || (*ptr1 == '@') || (*ptr1 == '&') || (*ptr1 == ')') || (*ptr1 == '(') || (*ptr1 == ',') || (*ptr1 == '#')) {
	  *(ptr2++) = *ptr1;
        } else {
	  if(*ptr1 == '/') {
	    *(ptr2++) = '/';
	  } else {
	    if(*ptr1 == '.') {
	      *(ptr2++) = '.';
	    } else {
	      if((*ptr1 == '_') || (*ptr1 == ' ')) {
	        *(ptr2++) = '_';
	      } else {
                if((*ptr1 == 'ä') || (*ptr1 == (char)0x84)) {
		  *(ptr2++) = 'a'; *(ptr2++) = 'e';
	        } else {
		  if((*ptr1 == 'Ä') || (*ptr1 == (char)0x8e)) {
		    *(ptr2++) = 'A'; *(ptr2++) = 'e';
		  } else {
		    if((*ptr1 == 'ö') || (*ptr1 == (char)0x94)) {
		      *(ptr2++) = 'o'; *(ptr2++) = 'e';
		    } else {
		      if((*ptr1 == 'Ö') || (*ptr1 == (char)0x99)) {
		        *(ptr2++) = 'O'; *(ptr2++) = 'e';
		      } else {
		        if((*ptr1 == 'ü') || (*ptr1 == (char)0x81)) {
			  *(ptr2++) = 'u'; *(ptr2++) = 'e';
		        } else {
			  if((*ptr1 == 'Ü') || (*ptr1 == (char)0x9a)) {
			    *(ptr2++) = 'U'; *(ptr2++) = 'e';
			  } else {
			    if((*ptr1 == 'ß') || (*ptr1 == (char)0xe1)) {
			      *(ptr2++) = 's'; *(ptr2++) = 's';
			    } else {
			      
			      sprintf(ptr2, "x%x", (unsigned char)(*ptr1));
			      while(*ptr2) ptr2++;
			    }
			  }
		        }
		      }
		    }
		  }
	        }
	      }
	    }
	  }
        }
      }
    }
    ptr1++;
  }
  *ptr2 = (char)0;
  
}

static int filename_needs_change(char *filename)
{
  int back = 0;
  char *ptr;
  
  ptr = filename;
  while((*ptr) && (back == 0)) {
    if((*ptr < 'A') || (*ptr > 'Z')) {
      if((*ptr < 'a') || (*ptr > 'z')) {
	if(*ptr != '0') {
	  if((*ptr < '1') || (*ptr > '9')) {
	    if(*ptr != '/') {
	      if(*ptr != '.') {
		if(*ptr != '_') {
		  if(*ptr != '-') {
		    if(*ptr != '+') {
		      if(*ptr != '$') {
		        if(*ptr != '~') {
			  if(*ptr != '!') {
			  if(*ptr != '@') {
			  if(*ptr != '&') {
			  if(*ptr != '(') {
			  if(*ptr != ')') {
			  if(*ptr != ',') {
			  if(*ptr != '#') {
		          back = 1;
			  }
			  }
			  }
			  }
			  }
			  }
			  }
		        }
		      }
		    }
		  }
		}
	      }
	    }
	  }
	}
      }
    }
    ptr++;
  } 
  return back;
}


static int path_exists(char *pathname)
{
  int back = 0;
  /* struct stat stbuf; */
  dk_stat_t dkstatbuf;
  
  if(dkstat_get(&dkstatbuf, pathname)) {
    back = 1;
  } 
  return back;
}

static int is_no_link(char *pathname)
{
  int back = 1; int i;
  i = dksf_get_filetype(pathname);
  if(i & DK_FT_SYMLINK) {
    back = 0;
  }
  return back;
}

static int rename_file(char *oldname, char *newname)
{
  int back = 1;
  
  if(in_test_mode) {
    printf("%s %s\n", oldname, newname);
  } else {
    if(path_exists(newname)) {
      back = 0;
    } else {
      if(rename(oldname, newname) != 0) {
	back = 0;
	printf("cona: ERROR - Failed to rename \"%s\" to \"%s\"\n",
	  oldname, newname
	);
      }
    }
  } 
  return back;
}

static int run_for_entry(char *filename)
{
  int back = 1;
  char tempfilename[MAXPATHLEN];
  BackTrack *first, *current;
  
  first = current = NULL;
  if(filename[0] != '-') { 
    if(strlen(filename) < MAXPATHLEN) { 
      if(filename_needs_change(filename)) { 
	create_new_filename(filename); 
	if(strlen(newname) < MAXPATHLEN) { 
	  if(!rename_file(filename, newname)) { 
	    back = 0;
	  } else { 
	  }
	} else {
	  back = 0;
	}
      } else {
	strcpy(newname, filename);
      }
      if(back) { 
	if(dksf_is_directory(newname) && is_no_link(newname)) {
	  
	  first = current = backtrack_new();
	  if(current) { 
	    strcpy(current->pathname, newname);
	    while(current) { 
	      switch(current->state) {
		case 0: {
		  DIR *dir;
		  struct dirent *dirp;
		  int must_continue, can_continue;
		  
		  do {
		    must_continue = 0;
		    dir = opendir(current->pathname);
		    if(dir) { 
		      can_continue = 1;
		      while(can_continue) { 
			dirp = readdir(dir);
			if(dirp) { 
			  if(filename_needs_change(dirp->d_name)) {
			    
			    if((strlen(current->pathname) + strlen(dirp->d_name) + 1) < MAXPATHLEN) {
			      
			      strcpy(tempfilename, current->pathname);
			      strcat(tempfilename, "/");
			      strcat(tempfilename, dirp->d_name);
                              create_new_filename(tempfilename);
			      if(strlen(newname) < MAXPATHLEN) {
				
				if(rename_file(tempfilename, newname)) {
				  
				  if(!in_test_mode) {
				    can_continue = 0;
				    must_continue = 1;
				  }
				} else {
				  
				  back = 0;
				}
			      } else {
				
				back = 0;
			      }
			    } else { 
			      back = 0;
			    }
			  }
			} else { 
			  can_continue = 0;
			}
		      }
		      closedir(dir);
		    } else {
		      back = 0; current->state = 3;
		    }
		  } while(must_continue);
		  current->state = 1;
		} break;
		case 1: {
		  
		  current->dir = opendir(current->pathname);
		  if(current->dir) { 
		    current->state = 2;
		  } else { 
		    current->state = 3; back = 0;
		  }
		} break;
		case 2: {
		  struct dirent *dirp;
		  BackTrack *n;
		  
		  dirp = readdir(current->dir);
		  if(dirp) { 
		    if(strcmp(dirp->d_name, ".") && strcmp(dirp->d_name, "..")) {
		      
		      if((1 + strlen(current->pathname) + strlen(dirp->d_name)) < MAXPATHLEN) {
			
			strcpy(tempfilename, current->pathname);
			strcat(tempfilename, "/");
			strcat(tempfilename, dirp->d_name);
			if(dksf_is_directory(tempfilename)) {
			  
                          n = backtrack_new();
			  if(n) { 
			    strcpy(n->pathname, tempfilename);
			    n->last = current;
			    current = n;
			  } else {
			    
			    back = 0;
			  }
			}
		      } else { 
			back = 0;
		      }
		    }
		  } else {
		    closedir(current->dir); current->dir = NULL;
		    current->state = 3;
		  }
		} break;
		case 3: {
		  BackTrack *n;
		  
		  n = current->last;
		  
		  backtrack_free(current);
		  current = n;
		  
		} break;
	      }
	    }
	  } else {
	    back = 0;
	  }
	}
      }
    } else {
      back = 0;
    }
  } else {
    if(strcmp(filename, "-test") == 0) {
      in_test_mode = 1;
    }
    if(strcmp(filename, "-notest") == 0) {
      in_test_mode = 0;
    }
  } 
  return back;
}

static int run(int argc, char **argv)
{
  int back = 1;
  char **argptr; int i;
  argptr = argv; i = argc;
  while(i--) {
    if(run_for_entry(*(argptr++)) == 0) {
      back = 0;
    }
  }
  return back;
}

int main(int argc, char *argv[])
{
  int exval = 1;
  char **argptr; int i;
  
#line 472 "cona.ctr"

  if(argc > 1) {
    argptr = argv; i = argc;
    argptr++; i--;
    exval = run(i, argptr);
    exval = (exval ? 0 : 1);
  }
  
#line 479 "cona.ctr"

  exit(exval); return exval;
}

