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

#include "../global.h"
#include "shared_cs_util.h"
#include "shared_system_data.h"


/** INCLUDE_SERVER_PORT_IN_URLS, USE_HTTPS, HTTPS_PORT and HTTP_PORT are
*** #defined in system_conf_data 
***
*** This function should be called whenever Manhattan has to generate a 
*** full URL back to one of its own programs.  The result is sent back
*** via server_string, max_len represents the maximum length of that 
*** string, which probably should be MAX_PATH + 1
***
*** Via #define USE_HTTPS  in system_conf_data, the system can be set up to REQUIRE
*** a secure connection.  However even if that is turned off, users should
*** still be allowed to access Manhattan with an https:// prefix.
*** Thus, if the SERVER_PORT environment variable sent to this CGI is equal
*** to the HTTPS_PORT specified in system_conf_data, the returned URL will be a 
*** https:// connection.
**/
void
get_server_string(char *server_string, int maxlen)
{

 int current_port;
 char *str =0;

 str = hdf_get_value(global_cgi->hdf, "CGI.ServerPort", 0);
 if(str && strlen(str))
   current_port = atoi(str);
 str = hdf_get_value(global_cgi->hdf, "CGI.ServerName", 0);
 
 if(system_data_int("INCLUDE_SERVER_PORT_IN_URLS"))
  {
    snprintf(server_string, maxlen, "%s://%s:%d", 
       ((current_port == system_data_int("HTTPS_PORT")) || system_data_int("USE_HTTPS"))? "https":"http", 
       str,
       system_data_int("USE_HTTPS")? system_data_int("HTTPS_PORT"): system_data_int("HTTP_PORT"));
  }
 else
    snprintf(server_string, maxlen, "%s://%s",
       ((current_port== system_data_int("HTTPS_PORT")) || system_data_int("USE_HTTPS"))? "https":"http", 
            str);
  
  *(server_string + maxlen - 1) = '\0';   /* force to be null terminated */
 }       


