/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc.  Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 *
 * 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; version 2
 * of the License.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * END COPYRIGHT BLOCK **/
/*
 * referer.c - Handle issues with going back from whence you came
 *
 * All blame to Mike McCool
 * Totally rewritten by Fred Cox, under guidance by above.
 */

#include "libadmin/libadmin.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "prprf.h"

#define REFER_VAR "adminReferer"

NSAPI_PUBLIC char *
get_referer( char **qqqq )
{
  return cookieValue( REFER_VAR, NULL );
}

static char *
fixAddition( char *url, char *addition )
{
  if ( addition ) {
    char	*result = (char *)MALLOC( strlen( url ) + strlen( addition ) + 1 );
    int		i;

    for ( i = 0 ; url[i] && url[i] != '?' ; ++i ) {
      result[i] = url[i];
    }
    result[i] = '?';
    result[i+1] = '\0';
    strcat( result, addition );

    return result;
  } else {
    return STRDUP( url );
  }
}

NSAPI_PUBLIC void
redirect_to_referer( char *addition )
{
  char	*url;
  char  *ref;

  ref = cookieValue( REFER_VAR, NULL );

  url = fixAddition(ref, addition );

  fprintf( stderr, "Content-type: text/html\n\n"
	   "<SCRIPT type=\"text/"MOCHA_NAME"\">\n"
	   "window.location='%s';\n"
	   "</SCRIPT>\n", url );
  FREE( url );
}

NSAPI_PUBLIC void
js_open_referer( void )
{
    char *ref;

    ref = cookieValue( REFER_VAR, NULL );

    fprintf( stdout,
	     "<SCRIPT type=\"text/"MOCHA_NAME"\">\n"
	     "window.location='%s'\n"
	     "</SCRIPT>\n", ref );
}

/* Blame Rob. */
NSAPI_PUBLIC void redirect_to_script(char *script)
{
    char urlbuf[BIG_LINE];
    char *ptr;

    PR_snprintf(urlbuf, sizeof(urlbuf), "%s%s", getenv("SERVER_URL"), getenv("SCRIPT_NAME"));
    if ((ptr = strrchr(urlbuf, '/'))) {
        int maxsize = sizeof(urlbuf)-((ptr-urlbuf)+2); /* one for the '/' and one for the '0' */
        PL_strncpyz(ptr + 1, script, maxsize);
    } else {
        PR_snprintf(urlbuf, sizeof(urlbuf), "%s/%s", getenv("SERVER_URL"), script);
    }
    printf("Location: %s\n\n", urlbuf);
}
