/*
 * @($) $Id: pwfile.c,v 1.3 2007-02-27 14:10:08 geirha Exp $
 *
 * functions for parsing the config file.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/resource.h>
#include "mysql-admutils.h"
#include "pwyacc.h"

/* the MySQL maximum */
#define MAXPWCHARS 16

/* defaults for configurable values */
const char* db_user = "root";
const char* db_server = "localhost";
const char* db_passwd = NULL;
const char* db_name = "mysql";

extern int yyparse(void);
extern FILE *yyin;

int config_line = 1;

static FILE *pwfile;
static char *filename = SYSCONFDIR "/mysql-admutils.conf";

int
read_config_file(void)
{
  struct rlimit rlim;
  int rc; /* return code */

  /* to stop the user from obtaining the password from a core dump. */
  if (getrlimit(RLIMIT_CORE, &rlim) == -1) {
    perror("getrlimit");
    exit(1);
  }
  rlim.rlim_max = 0;
  if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
    perror("setrlimit");
    exit(1);
  }

  pwfile = fopen(filename, "r");
  if (!pwfile) {
    fatal_error("cannot open configuration file %s", filename);
    exit(1);
  }

  /* we don't need to be SUID anymore. */
  if (seteuid(getuid()) != 0)
    perror("seteuid");

  yyin = pwfile;
  rc = yyparse();
  fclose(pwfile);

  return rc;
}


int
yywrap(void)
{
  return 1;
}


int
yyerror(const char *msg)
{
  fprintf(stderr, "%s:%d: %s\n", filename, config_line, msg);
  return 0;
}


int
config_set_string_var(int var, const char *value)
{
  assert(value);
  switch (var) {
  case USER:
    db_user = value;
    break;
  case HOST:
    db_server = value;
    break;
  case PASSWORD:
    if (strlen(value) > MAXPWCHARS) {
      fprintf(stderr, "%s:%d: password is too long (%d chars > %d chars)\n", 
	      filename, config_line, strlen(value), MAXPWCHARS);
      fclose(pwfile);
      exit(1);
    }
    db_passwd = value;
    break; 
  default:
    assert(!"We should never get here.");
  }
  return 0;
}