#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include "meta.h"

int policy_ignore(char *ip)
{
  char name[64];
  sprintf(name, "udp/ignore/%s", ip);
  return access(name, F_OK) == 0;
}

int policy_local_only() {
  return access("udp/local-only", F_OK) == 0;
}

int policy_limit(char *ip, char *hostname) 
{
  char name[64];
  sprintf(name, "udp/limit/%s", ip);
  if (access(name, F_OK) == 0) {
    return 1;
  } else {
    snprintf(name, 63, "udp/limit/%s", hostname);
    if (access(name, F_OK) == 0) {
      return 1;
    }
  }
  return 0;
}

/* called when a server update is received */
void policy_updated_server(SERVER *sp)
{
  char name[64];

  /* propogate spare flag to server entry */
  snprintf(name, 63, "udp/spare/%s", sp->hostname);
  sp->spare = (access(name, F_OK) == 0);

  /* propogate prefer flag to server entry */
  snprintf(name, 63, "udp/prefer/%s", sp->hostname);
  sp->prefer = (access(name, F_OK) == 0);
}

/* whether to show a server based on policy decisions */
int policy_show(SERVER *sp)
{
  time_t now = time(NULL);
  int age = now - sp->last_update;

  /* do not list old INL solicited servers */
  if (sp->type[0] == 'I' && sp->solicit && age > 600) return 0;

  /* do not list old active servers */
  /* to catch servers that die during an active game */
  if (sp->player_count > 0 && age > 3600) return 0;

  /* do not list old inactive servers */
  /* to catch servers that are removed and become uncontactable */
  if (sp->player_count == 0 && age > (60*60*6)) return 0;

  /* if this server is not a spare, show it */
  if (!sp->spare) return 1;

  /* otherwise, only show spares if at least one preferred has players */
  SERVER *osp;
  int i = 0;

  for (i = 0, osp = servers; i < server_count; i++, osp++) {
    if (osp->prefer && osp->player_count > 11) return 1;
  }
  return 0;
}

/* allow for servers to be aliased */
void policy_alias(SERVER *sp)
{
  char name[64], ip[32];
  FILE *file;
  char *line;

  /* if an alias file does not exist, continue */
  sprintf(name, "udp/alias/%s", sp->ip_addr);
  if (access(name, R_OK) != 0) return;

  /* an alias file exists, use the alias ip inside it */
  file = fopen(name, "r");
  if (file == NULL) return;
  line = fgets(ip, 31, file);
  fclose(file);
  if (line == NULL) return;

  /* strip the newline */
  line = strrchr(ip, '\n');
  if (line != NULL) *line = '\0';

  /* override the ip */
  strcpy(sp->ip_addr, ip);
}
