/*

    tagit 3.1 - Appends a random quote to a mail signature

    Copyright (C) 1991-2001 Angel Ortega <angel@triptico.com>

    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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    http://www.triptico.com

    New in 3.1
    ==========

    Now you can have multiple quote files named ~/quotes0, ~/quotes1 to
    infinity and one of them will be selected randomly. Otherwise the
    old ~/quotes will be used.

    Tagit & mutt
    ============

    To use tagit with mutt, just append

    send-hook . set signature=tagit|

    to your .muttrc and that's all (of course, you need ~/.signature and
    ~/.quotes* files ).

*/


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char buffer[1024];
char title[1024];

#define SIG_FILE		"/.signature"
#define DEFAULT_QUOTES_FILE	"/.quotes"


int main(int argc, char * argv[])
{
	FILE * f;
	int c,oc;
	int o,s;
	char * home;
	int n;

	if((home=getenv("HOME"))==NULL)
	{
		fprintf(stderr,"Can't get $HOME");
		exit(1);
	}

	snprintf(buffer,sizeof(buffer), "%s%s", home, SIG_FILE);

	/* writes signature */
	if((f=fopen(buffer,"r"))!=NULL)
	{
		while((c=fgetc(f))!=EOF)
			putc(c,stdout);

		fclose(f);
		printf("\n");
	}

	/* sets random seed */
	srand(time(NULL));

	if(argc==1)
	{
		/* search home for files matching quotes%d */
		for(n=0;;n++)
		{
			snprintf(buffer, sizeof(buffer),
				"%s%s%d", home, DEFAULT_QUOTES_FILE, n);

			if((f=fopen(buffer,"r"))==NULL)
				break;
			else
				fclose(f);
		}

		if(n)
		{
			o=(n==1 ? 0 : rand() % n);

			snprintf(buffer, sizeof(buffer),
				"%s%s%d", home, DEFAULT_QUOTES_FILE, o);
		}
		else
			/* none; try just ~/quotes */
			snprintf(buffer, sizeof(buffer),
				"%s%s", home, DEFAULT_QUOTES_FILE);
	}
	else
	{
		o=rand() % (argc - 1);
		strncpy(buffer, argv[o+1], sizeof(buffer));
	}

	if((f=fopen(buffer,"r"))==NULL)
	{
		fprintf(stderr,"Can't open '%s'\n",buffer);
		exit(1);
	}

	fgets(title,sizeof(title),f);

	fseek(f,0,SEEK_END);
	s=ftell(f);

	o=rand() % s;

	fseek(f,o,SEEK_SET);

	/* seeks two joined \n */
	for(oc=-1;(c=fgetc(f))!=EOF;oc=c)
	{
		if(c=='\n' && oc=='\n')
			break;
	}

	/* write until another two \n */
	for(oc=-1;(c=fgetc(f))!=EOF;oc=c)
	{
		putc(c,stdout);
		if(c=='\n' && oc=='\n')
			break;
	}

	fclose(f);

	printf("%s",title);

	return(0);
}

