/* $Cambridge: hermes/src/prayer/cmd/cmd_exit.c,v 1.2 2008/05/19 15:55:54 dpc22 Exp $ */
/************************************************
 *    Prayer - a Webmail Interface              *
 ************************************************/

/* Copyright (c) University of Cambridge 2000 - 2008 */
/* See the file NOTICE for conditions of use and distribution. */

#include "prayer_session.h"

void cmd_exit(struct session *session)
{
    struct user_agent *user_agent = session->user_agent;
    struct config *config = session->config;
    struct request *request = session->request;
    char *url;

    session->want_disconnect = T;

    session_streams_close(session);

    session_log(session, "[cmd_exit] User logout");

    /* Back to login screen */

    if (config->hostname_service) {
        if (session->use_ssl) {
            if (session->frontend_port == 443)
                url = pool_printf(request->pool,
                                  "https://%s", config->hostname_service);
            else
                url = pool_printf(request->pool, "https://%s:%lu",
                                  config->hostname_service,
                                  session->frontend_port);
        } else {
            if (session->frontend_port == 80)
                url = pool_printf(request->pool,
                                  "http://%s", config->hostname_service);
            else
                url = pool_printf(request->pool, "http://%s:%lu",
                                  config->hostname_service,
                                  session->frontend_port);
        }
    } else
        url = session->url_prefix;

    if (user_agent->use_debug)
        url = pool_strcat(request->pool, url, "/debug");

    if (session->use_cookie && config->http_cookie_use_port) {
        char *path =
            pool_strcat(request->pool, "/session/", session->username);
        char *key;

        if (config->http_cookie_use_port)
            key = pool_printf(request->pool, "%s:%lu",
                              session->username, session->session_port);
        else
            key = session->username;

        response_clear_cookie_redirect(request, url,
                                       key, session->sessionid,
                                       path, config->hostname,
				       session->use_ssl);
    } else
        response_redirect(request, url);
}
