/* Author: Ram Samudrala (me@ram.org)
 * Version: O1.0
 * Detail: <http://www.ram.org/computing/redirector/redirector.html>
 * November 22, 1996.
 *
 * See the URL above for more information.
 *
 */

#define REDIRECTOR_MAPPING_FILE "/home/ram/www/computing/redirector/redirector_mapping_file"

#include "cgi_common.h"
#include "cgi_defines.h"
#include "cgi_error_handlers.h"
#include "cgi_display.h"

int content_type_displayed = FALSE;

static int help(char program_name[]);
static int get_url(char name[], char url[]);

/******************************************************************/

int main(int argc, char *argv[])
{
  entry entries[MAX_ENTRIES];
  int number_of_entries, i;
  char url[STRING_LENGTH];

  if (argc > 2)
    return help(argv[0]);

  if (argc == 2)
    {
      printf("Location: %s%s", argv[1], HEADER_DELIMITER);
      printf("%s", HEADER_DELIMITER);
      return TRUE;
    }
  
  check_method("POST", "main");
  check_content_type("main");
  number_of_entries = read_entries(entries);
  for(i = 0; i <= number_of_entries; i++)
    if (entries[i].val[0] != '\0')
      {
	get_url(entries[i].val, url);
	printf("Location: %s%s", url, HEADER_DELIMITER);
	printf("%s", HEADER_DELIMITER);
	return TRUE;
      }
  return TRUE;
}

/******************************************************************/

int help(char program_name[])
{
  char buf[STRING_LENGTH];
  
  sprintf(buf, "Usage: %s[+url]", program_name);
  display_error(buf);
  return FALSE;
}
      
/******************************************************************/

int get_url(char name[], char url[])
{
  FILE *input_fp;
  char line[LINE_LENGTH], *cp;
			     
  open_file(&input_fp, REDIRECTOR_MAPPING_FILE, "r", "get_url");
  while(fgets(line, LINE_LENGTH, input_fp))
    if ((line[0] != '\0') && (line[0] != '#') && (line[0] != '\n'))
      if ((cp = strstr(line, "|")) != NULL)
	{
	  cp++;
	  cp++;
	  line[strlen(line)-1] = '\0';
	  if (strstr(name, cp) != NULL)
	    {
	      sscanf(line, "%s", url);
	      return TRUE;
	    }
	}
  close_file(&input_fp, REDIRECTOR_MAPPING_FILE, "get_url");
  return TRUE;
}

/******************************************************************/
