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

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


/** INCLUDE_SERVER_PORT_IN_URLS, USE_HTTPS, HTTPS_PORT and HTTP_PORT are
*** #defined in custom.h 
***
*** 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 custom.h, 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 custom.h, 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(INCLUDE_SERVER_PORT_IN_URLS)
  {
    snprintf(server_string, maxlen, "%s://%s:%d", 
       ((current_port == HTTPS_PORT) || USE_HTTPS)? "https":"http", 
       str,
       USE_HTTPS? HTTPS_PORT: HTTP_PORT);
  }
 else
    snprintf(server_string, maxlen, "%s://%s",
       ((current_port==HTTPS_PORT) || USE_HTTPS)? "https":"http", 
            str);
  
  *(server_string + maxlen - 1) = '\0';   /* force to be null terminated */
 }       


