/**************************************************
OpengateM - MAC address authentication system 
 opengatem forwarding CGI main

 Program for responding to the first forwarding HTTP access.
 'index.html.var' must be set to start this program
 IPFW forwards HTTP packets to 'index.html.var' by the setting of httpd.conf.

---sample index.html.var---
URI: /cgi-bin/opengate/opengatemfwd.cgi?en
Content-language: en
Content-type: text/html

URI: /cgi-bin/opengate/opengatemfwd.cgi?ja
Content-language: ja
Content-type: text/html

URI: /cgi-bin/opengate/opengatemfwd.cgi?en
Content-type: text/html
---------------------------

Copyright (C) 2012 Opengate Project Team
Written by Yoshiaki Watanabe

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; either version 2
of the License, or (at your option) any later version.

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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

Email: watanaby@is.saga-u.ac.jp
**************************************************/

#include "opengatemmng.h"

int  main(int argc, char **argv)
{
  char htmlFile[BUFFMAXLN]="";   /* html file */
  char lang[ADDRMAXLN]=""; /* client language */
  char jumpCgiUrl[BUFFMAXLN];  /* url of forwarding destination */
  char redirectedUrl[BUFFMAXLN]; /* url of redirected(requested) page */
  char *protocol;
  char *httpHost;
  char *requestUri;
  FILE *fp;
  char buff[BUFFMAXLN];

  /* drop root privilege */
  seteuid(getuid());

  /* if this is executed in shell with '-v' option, show makedir */  
  if(argc>1){
    if(strcmp(argv[1],"-v")==0){
      printf("makedir: %s\n", MAKEDIR);
    }else{
      printf("This is cgi program\n");
      printf("To show version, run this on console with '-v' option\n");
    }
    exit(0);
  }

  /* prepare config file */
  if(OpenConfFile()==-1)return 0;
 
  /* start log */
  errToSyslog(atoi(GetConfValue("Syslog/Enable")));
  openlog(GetConfValue("FwdCgi"), LOG_PID, atoi(GetConfValue("Syslog/Facility")));

  /* initialize config */
  InitConf();

  if(debug>1) err_msg("DEBUG: started");

  /* favicon.ico request is ignored */
  if(!isNull(getenv("REQUEST_URI"))){
    if(strcmp(getenv("REQUEST_URI"), "/favicon.ico")==0){
      PutMessageToClient("");
      return 0;
    }
  }


  /* create URL string for jump cgi */
  snprintf(jumpCgiUrl, BUFFMAXLN, "%s%s%s/%s",
	   GetConfValue("OpengateServerName"),
	   GetConfValue("CgiDir"),
	   GetConfValue("OpengateDir"),
	   GetConfValue("JumpCgi"));

  /* if null element is included, put error */
  if(isNull(GetConfValue("OpengateServerName")) ||
     isNull(GetConfValue("CgiDir")) ||
     isNull(GetConfValue("OpengateDir")) ||
     isNull(GetConfValue("JumpCgi")) ){
    err_msg("ERR at %s#%d: jump url cannot setup properly from conf[%s]",__FILE__,__LINE__, jumpCgiUrl);
      PutMessageToClient("error: refer conf file");
      return 0;
  }

  /* get language from environment variable set with httpd(see index.html.var) */
  if(isNull(getenv("QUERY_STRING"))){
    lang[0]='\0';
  }else{
    strlcpy(lang, getenv("QUERY_STRING"), ADDRMAXLN);
  }
     
  /* if not get, use default language at the top of language list */
  if(isNull(lang)){
    sscanf(GetConfValue("HtmlLangs"),"%s",lang);
  }
     
  /* if the language is not registered in language list, */
  /* set the first language in the list */
  else if(strstr(GetConfValue("HtmlLangs"), lang)==NULL){
    sscanf(GetConfValue("HtmlLangs"),"%s",lang);
  }

  /* construct redirected(requested) URL */
  /* protocol */
  if(!isNull(getenv("SERVER_PORT"))
     && strcmp(getenv("SERVER_PORT"),GetServicePortStr("https"))==0) {
    protocol="https";
  }else{
    protocol="http";
  }

  /* http-host */
  if(!isNull(getenv("HTTP_HOST"))) httpHost=getenv("HTTP_HOST");
  else httpHost="";

  /* request-uri */
  if(!isNull(getenv("REQUEST_URI"))) requestUri=getenv("REQUEST_URI");
  else requestUri="";

  /* concat above items to make redirect URL */
  if(!isNull(httpHost)){
    snprintf(redirectedUrl,BUFFMAXLN,"%s://%s%s", protocol,httpHost,requestUri);
  }else redirectedUrl[0]='\0';

  /* construct html template file path */
  snprintf(htmlFile, BUFFMAXLN, "%s%s/%s/%s", 
	  GetConfValue("DocumentRoot"), 
	  GetConfValue("OpengateDir"),
	  lang, 
	  GetConfValue("FwdDoc"));

  /* if null element is included, put error */
  if(isNull(GetConfValue("DocumentRoot")) ||
     isNull(GetConfValue("OpengateDir")) ||
     isNull(GetConfValue("FwdDoc")) ){
    err_msg("ERR at %s#%d: fwd doc path cannot setup properly from conf[%s]",__FILE__,__LINE__, htmlFile);
      PutMessageToClient("error: refer conf file");
      return 0;
  }

  /* send out header */
  printf("Content-Type: text/html\r\n\r\n\r\n");

  /* open html template file */
  if((fp=fopen(htmlFile, "r"))==NULL){
    err_msg("ERR at %s#%d: cannot find file [%s]",__FILE__,__LINE__, htmlFile);
    return FALSE;
  }

  /* replace keywords in template file and send out */
  while(fgets(buff,BUFFMAXLN,fp)!=NULL){
    HtmlReplace(buff, "%%JUMPCGIURL%%", jumpCgiUrl);
    HtmlReplace(buff, "%%REDIRECTEDURL%%", redirectedUrl);
    if(strstr(buff, "%%ERRORLIST%%")!=NULL){
      InsertMessageToPage(lang);
    }else{
      printf("%s",buff);    
    }
  }
  fclose(fp);

  if(debug>1) err_msg("DEBUG: terminated");

  return 0;
}
