/****************************************************************/
/* Utils unit                                                   */
/* (c) Christophe CALMEJANE (Ze KiLleR) - 1999-01               */
/****************************************************************/
#include "skyutils.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

extern char *SW_UserHeader;

#ifdef DUMP
int SU_DebugLevel = 5;
#elif DEBUG
int SU_DebugLevel = 4;
#else
int SU_DebugLevel = 0;
#endif

FILE *SU_OpenLogFile(const char LogName[])
{
  return fopen(LogName,"at");
}

void SU_CloseLogFile(FILE *fp)
{
  if(fp != NULL)
    fclose(fp);
}

void SU_WriteToLogFile(FILE *fp,const char Text[])
{
  struct tm *TM;
  time_t Tim;

  if(fp != NULL)
  {
    Tim = time(NULL);
    TM = localtime(&Tim);
    fprintf(fp,"[%.4d/%.2d/%.2d-%.2d:%.2d:%.2d] %s\n",TM->tm_year+1900,TM->tm_mon+1,TM->tm_mday,TM->tm_hour,TM->tm_min,TM->tm_sec,Text);
  }
}

/* Skip the username and password, if present here.  The function
   should be called *not* with the complete URL, but with the part
   right after the protocol.

   If no username and password are found, return 0.  */
static int skip_uname (const char *url)
{
  const char *p;
  for (p = url; *p && *p != '/'; p++)
    if (*p == '@')
      break;
  /* If a `@' was found before the first occurrence of `/', skip
     it.  */
  if (*p == '@')
    return p - url + 1;
  else
    return 0;
}

static void parse_uname (const char *url, char *user, char *passwd)
{
  const char *p, *col;

  /* Is there an `@' character?  */
  for (p = url; *p && *p != '/'; p++)
    if (*p == '@')
      break;
  /* If not, return.  */
  if (*p != '@')
    return;

  /* Else find the username and password.  */
  for (p = col = url; *p != '@'; p++)
    {
      if (*p == ':')
        {
          memcpy (user, url, p - url);
          user[p - url] = '\0';
          col = p + 1;
        }
    }
  memcpy (passwd, col, p - col);
  passwd[p - col] = '\0';
}

/* Checks the http_proxy env var */
void SU_CheckProxyEnv(void)
{
  char *proxy_env,*tok;
  char  proxy_server_name[256];
  char  proxy_server_user[256];
  char  proxy_server_password[256];
  int   proxy_server_port=8080;

  proxy_env = getenv("http_proxy");
  if((proxy_env != NULL) && (strlen(proxy_env)>0))
  {
    char *proxy_save;
    char *proxy_val;

    memset(proxy_server_name,0,256);
    memset(proxy_server_user,0,256);
    memset(proxy_server_password,0,256);
    /*
     * Proxy URL is in the form :  [http://][user:password@]server:port[/]
     * Skip the "http://" if it's present
     */
    if(!strncasecmp(proxy_env,"http://",7)) proxy_env+=7;
    proxy_save = strdup(proxy_env);

    /*
     * Allow a username and password to be specified (i.e. just skip
     * them for now).
     */
    proxy_val = proxy_env+skip_uname (proxy_env);
    tok=strtok(proxy_val,":");
    if(tok) strncpy(proxy_server_name,tok,256);
    tok=strtok(NULL,"/");
    if(tok) proxy_server_port=atoi(tok);

    /* Parse the username and password (if existing).  */
    parse_uname (proxy_save, proxy_server_user, proxy_server_password);

    SU_SetProxy(proxy_server_name,proxy_server_port,proxy_server_user,proxy_server_password);
    free(proxy_save);
  }
}

/* Remove arguments for skyutils, and returns number of remaining arguments for smssend */
int SU_GetSkyutilsParams(int argc,char *argv[])
{
  int i = 1,nb;
  char *pos;
  int Port = 0;
  int Timeout = 0;
  int Lv = 0;
  char *ProxyName = NULL;
  char *UserName = NULL;
  char *Password = NULL;
  bool proxy = false;

  nb = argc;
  while(i < argc)
  {
    if(strcmp(argv[i],"--") == 0) /* SkyUtils arguments */
    {
      nb = i;
      i++;
      while(i < argc)
      {
        if(strcmp(argv[i],"--") == 0) /* No more SkyUtils arguments */
          break;
        else if(strncmp(argv[i],"-d",2) == 0) /* Debug level */
        {
          Lv = atoi(argv[i] + 2);
          SU_SetDebugLevel(Lv);
        }
        else if(strncmp(argv[i],"-t",2) == 0) /* Socket timeout */
        {
          Timeout = atoi(argv[i] + 2);
          SU_SetSocketTimeout(Timeout);
        }
        else if(strncmp(argv[i],"-h",2) == 0) /* User's header file */
        {
          SW_UserHeader = SU_LoadUserHeaderFile(argv[i] + 2);
        }
        else if(strncmp(argv[i],"-p",2) == 0) /* Proxy name:port */
        {
          pos = strchr(argv[i],':');
          if(pos == NULL)
            printf("SkyUtils warning : Error parsing proxy argument for skyutils, disabling proxy\n");
          else
          {
            Port = atoi(pos+1);
            pos[0] = 0;
            ProxyName = argv[i] + 2;
          }
        }
        else if(strncmp(argv[i],"-u",2) == 0) /* Proxy user:pass */
        {
          pos = strchr(argv[i],':');
          if(pos == NULL)
            printf("SkyUtils warning : Error parsing proxy username argument for skyutils, disabling proxy\n");
          else
          {
            Password = pos + 1;
            pos[0] = 0;
            UserName = argv[i] + 2;
          }
        }
        i++;
      }
      break;
    }
    i++;
  }
  if((ProxyName == NULL) && (UserName != NULL))
  {
    printf("SkyUtils warning : Username for proxy specified, but no proxy given, disabling proxy\n");
  }
  else if(ProxyName != NULL)
  {
    SU_SetProxy(ProxyName,Port,UserName,Password);
    proxy = true;
  }
  if(!proxy)
    SU_CheckProxyEnv();
  return nb;
}

char *SU_LoadUserHeaderFile(const char FName[])
{
  FILE *fp;
  char *buf;
  char S[1024];
  int len;

  fp = fopen(FName,"rt");
  if(fp == NULL)
  {
    printf("SkyUtils warning : Cannot load user's header file %s\n",FName);
    return NULL;
  }
  buf = NULL;
  len = 1; /* For the \0 */
  while(SU_ReadLine(fp,S,sizeof(S)))
  {
    if(S[0] == 0)
      continue;
    len += strlen(S) + 2; /* +2 for \n */
    if(buf == NULL)
    {
      buf = (char *) malloc(len);
      SU_strcpy(buf,S,len);
    }
    else
    {
      buf = (char *) realloc(buf,len);
      SU_strcat(buf,S,len);
    }
    SU_strcat(buf,"\x0D" "\x0A",len);
  }
  fclose(fp);
  return buf;
}

void SU_SetDebugLevel(int Lv)
{
  SU_DebugLevel = Lv;
}

int SU_GetDebugLevel(void)
{
  return SU_DebugLevel;
}

char *SU_GetOptionsString(void)
{
  return "-pproxy:port -uusername:password -tTimeout -dDebugLevel -hHeaderFile";
}

void SU_Dummy111(void) {}
void SU_Dummy112(void) {}
