#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "file.h"

FILE *fileopen(char *file, char *mode){
   FILE *p;
   p=fopen(file,mode);
   if(!p){
      fprintf(stderr,"Failed to open %s (mode=%s)\n",file,mode); exit(1);
   }
   return p;
}

Boolean file_exist(char *file){
   FILE *p;
   p=fopen(file,"r");
   if(p==NULL) return FALSE;
   else fclose(p);
   return TRUE;
}

int file_nline(char *file){
   int nline;
   FILE *fp;
   char *command;
   if(file_exist(file)==FALSE) return 0;
   command=malloc((strlen(file)+10)*sizeof(char));
   sprintf(command,"wc -l %s",file);
   fp=popen(command,"r");
/*
   if((fp=popen(command,"r"))==NULL){
      fprintf(stderr,"Failed to excecute '%s'\n",command); exit(1);
   }
*/
   fscanf(fp,"%d",&nline);
   pclose(fp);
   free(command);
   return nline;
}

Boolean comment_line(char *line){
   if(line[0]=='#') return TRUE;
   return FALSE;
}

Boolean check_dir(char *dir){
   struct stat st;
   if(stat(dir,&st)){
      fprintf(stderr,"Nothing named %s exists !\n",dir); return FALSE;
   }
   if(!S_ISDIR(st.st_mode)){
      fprintf(stderr,"%s is not a directory !\n",dir); return FALSE;
   }
   return TRUE;
}

Boolean check_file(char *file){
   struct stat st;
   if(stat(file,&st)) return FALSE;
   if(!stat(file,&st)&&!S_ISREG(st.st_mode)){
      fprintf(stderr,"%s exists, but it is not a regular file !\n",file); return FALSE;
   }
   return TRUE;
}

Boolean check_link(char *link){
   struct stat st;
   if(stat(link,&st)){
      fprintf(stderr,"Nothing named %s exists !\n",link); return FALSE;
   }
   if(!S_ISLNK(st.st_mode)){
      fprintf(stderr,"%s is not a link !\n",link); return FALSE;
   }
   return TRUE;
}

Boolean remove_file_if_exist(char *file){
   struct stat st;
   if(!stat(file,&st) && S_ISREG(st.st_mode)){
      remove(file); return TRUE;
   }
   return FALSE;
}

