/* 
   The JitterBug bug tracking system
   utility functions

   Copyright (C) Andrew Tridgell 1997

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "weblist.h"

/* lowercase a string */
void strlower(char *str)
{
	while (*str) {
		if (isupper(*str)) *str = tolower(*str);
		str++;
	}
}


/* check if a file is a directory */
int is_directory(char *dir)
{
	struct stat st;
	if (stat(dir, &st)) return 0;
	return S_ISDIR(st.st_mode);
}

/* check if a file exists */
int file_exists(char *fname, struct stat *st)
{
	struct stat st2;
	if (!st) st = &st2;
	if (stat(fname, st)) return 0;
	return 1;
}


/* return a string showing the current date and time */
char *timestring(void)
{
	struct tm *tm;
	static char tbuf[100];
	time_t t = time(NULL);

	tm = localtime(&t);

	strftime(tbuf,sizeof(tbuf)-1,"%c", tm);
	return tbuf;
}

/* show a selection list, including a blank element */
void select_list(char **list, char *vname, char *def)
{
	int i;

	printf("<select name=%s>\n", vname);
        printf("<option %s value=\"\">\n", (def && *def)?"":"SELECTED");
	for (i=0;list && list[i];i++) {
		char *s = quotequotes(list[i]);
		printf("<option %s value=\"%s\">%s\n", 
		       (def && strcmp(def, list[i])==0) ? "SELECTED":"",
		       s, s);
		free(s);
	}
	printf("</select>\n");
}

/* return a selection list, including a blank element */
char *sel_list(char **list, char *vname, char *def)
{
	char *ret, *p;
	int i, len=200;

	
	for (i=0;list && list[i];i++) {
		len += strlen(list[i])*2 + 50;
	}

	ret = (char *)malloc(len);
	if (!ret) fatal("Out of memory");

	p = ret;

	p += slprintf(p, (len-1)-(p-ret), "<select name=%s>\n", vname);
        p += slprintf(p, (len-1)-(p-ret), "<option %s value=\"\">\n", (def && *def)?"":"SELECTED");
	for (i=0;list && list[i];i++) {
		char *s = quotequotes(list[i]);
		p += slprintf(p, (len-1)-(p-ret), "<option %s value=\"%s\">%s\n", 
		       (def && strcmp(def, list[i])==0) ? "SELECTED":"",
		       s, s);
		free(s);
	}
	p += slprintf(p, (len-1)-(p-ret), "</select>\n");

	return ret;
}

int in_list(char **list, char *s)
{
	int i;
	if (!list) return 0;

	for (i=0;list[i];i++)
		if (strcasecmp(list[i], s)==0) return 1;
	return 0;
}

#ifndef HAVE_MEMMOVE
/*******************************************************************
safely copies memory, ensuring no overlap problems.
this is only used if the machine does not have it's own memmove().
this is not the fastest algorithm in town, but it will do for our
needs.
********************************************************************/
 void *memmove(void *dest,void *src,int size)
{
  unsigned long d,s;
  int i;
  if (dest==src || !size) return(dest);

  d = (unsigned long)dest;
  s = (unsigned long)src;

  if ((d >= (s+size)) || (s >= (d+size))) {
    /* no overlap */
    memcpy(dest,src,size);
    return(dest);
  }

  if (d < s)
    {
      /* we can forward copy */
      if (s-d >= sizeof(int) && 
	  !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
	/* do it all as words */
	int *idest = (int *)dest;
	int *isrc = (int *)src;
	size /= sizeof(int);
	for (i=0;i<size;i++) idest[i] = isrc[i];
      } else {
	/* simplest */
	char *cdest = (char *)dest;
	char *csrc = (char *)src;
	for (i=0;i<size;i++) cdest[i] = csrc[i];
      }
    }
  else
    {
      /* must backward copy */
      if (d-s >= sizeof(int) && 
	  !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
	/* do it all as words */
	int *idest = (int *)dest;
	int *isrc = (int *)src;
	size /= sizeof(int);
	for (i=size-1;i>=0;i--) idest[i] = isrc[i];
      } else {
	/* simplest */
	char *cdest = (char *)dest;
	char *csrc = (char *)src;
	for (i=size-1;i>=0;i--) cdest[i] = csrc[i];
      }      
    }
  return(dest);
}
#endif

#ifndef HAVE_STRDUP
/****************************************************************************
duplicate a string
****************************************************************************/
 char *strdup(char *s)
{
	char *ret = NULL;
	if (!s) return(NULL);
	ret = (char *)malloc(strlen(s)+1);
	if (!ret) return(NULL);
	strcpy(ret,s);
	return(ret);
}
#endif


/* remove jusk from front and back of a string */
void trim_string(char *s,char *front,char *back)
{
	while (front && *front && strncmp(s,front,strlen(front)) == 0) {
		char *p = s;
		while (1) {
			if (!(*p = p[strlen(front)]))
				break;
			p++;
		}
	}
	while (back && *back && strlen(s) >= strlen(back) && 
	       (strncmp(s+strlen(s)-strlen(back),back,strlen(back))==0)) {
		s[strlen(s)-strlen(back)] = 0;
	}
}

void check_overflow(int len, int space)
{
	if (len > space) fatal("buffer overflow %d %d\n", len, space);
}

char *d_name(struct dirent *di)
{
#if HAVE_BROKEN_READDIR
	return (di->d_name - 2);
#else
	return di->d_name;
#endif
}

int match_string(char *s, char *list)
{
	char *tok;
	if (!list || !s) return 0;
	list = strdup(list);

	for (tok=strtok(list," ,\t"); tok; tok=strtok(NULL," ,\t")) {
		if (strstr(s, tok)) {
			free(list);
			return 1;
		}
	}
	free(list);
	return 0;
}

/* a version of getenv that returns (NULL) if the variable does not exist */
char *getenv_null(char *ename)
{
	char *s = getenv(ename);
	if (!s) return "(NULL)";
	return s;
}

/* load a file as a string */
char *load_file(char *fname, struct stat *st, int max_size)
{
	int fd;
	struct stat st1;
	char *ret;

	if (!st) st = &st1;

	fd = open(fname,O_RDONLY);
	if (fd == -1) return NULL;

	if (fstat(fd, st)) {
		close(fd);
		return NULL;
	}

	ret = (char *)malloc(st->st_size + 1);
	if (!ret) {
		close(fd);
		return NULL;
	}

	if (max_size == 0 || max_size > st->st_size)
		max_size = st->st_size;

	if (read(fd, ret, max_size) != max_size) {
		close(fd);
		free(ret);
		return NULL;
	}

	ret[max_size] = 0;
	close(fd);
	return ret;
}


char *xstrdup(char *s)
{
	if (!s) s = "";
	s = strdup(s);
	if (!s) {
		exit(1);
	}
	return s;
}

char *xmalloc(int len)
{
	char *s = malloc(len);
	if (!s) {
		exit(1);
	}
	return s;
}

/* extract an email address from a from line. Note the peculiar processing
   of the < and > characters because the from line has already been through
   quotedup() */
char *extract_address(char *s)
{
	char *p1, *p2, *p3;
	char buf[100];
	if (strlen(s) > sizeof(buf)-1) return strdup(s);

	/* first try for something with <> around it */
	p1 = strstr(s,"&lt;");
	if (p1) {
		p1 += 4;
		p2 = strstr(p1,"&gt;");
		if (p2) {
			while ((p3 = strstr(p1,"&lt;")) && (p3 < p2)) {
				p1 = p3 + 4;
			}
			memcpy(buf, p1, p2-p1);
			buf[(int)(p2-p1)] = 0;
			return strdup(buf);
		}
	}

	/* first try for something with <> around it */
	p1 = strstr(s,"<");
	if (p1) {
		p1 += 1;
		p2 = strstr(p1,">");
		if (p2) {
			while ((p3 = strstr(p1,">")) && (p3 < p2)) {
				p1 = p3 + 1;
			}
			memcpy(buf, p1, p2-p1);
			buf[(int)(p2-p1)] = 0;
			return strdup(buf);
		}
	}

	/* now try for anything with an @ in it */
	p1 = strchr(s,'@');
	if (p1) {
		while (p1 > s && !isspace(*p1)) p1--;
		if (isspace(*p1)) p1++;
		p2 = p1+1;
		while (*p2 && !isspace(*p2)) p2++;
		memcpy(buf,p1, p2-p1);
		buf[(int)(p2-p1)] = 0;
		return strdup(buf);
	}
	
	/* otherwise grab the first thing */
	p1 = s;
	while (*p1 && isspace(*p1)) p1++;
	p2 = p1;
	while (*p2 && !isspace(*p2)) p2++;
	memcpy(buf,p1, p2-p1);
	buf[(int)(p2-p1)] = 0;

	return strdup(buf);
}

int pmatch(char *pattern, char *s)
{
	int ret;
	char *p;

	if (!pattern || !s) return 0;

	p = xmalloc(strlen(pattern)+3);
	if (*pattern != '*') {
		strcpy(p, "*");
		strcat(p, pattern);
	} else {
		strcpy(p, pattern);
	}
	pattern = p;
	if (pattern[strlen(pattern)-1] != '*') {
		strcat(pattern, "*");
	}
	s = xstrdup(s);

	strlower(pattern);
	strlower(s);

	ret = (fnmatch(pattern, s) == 0);

	free(pattern);
	free(s);

	return ret;
}
