//=-- PingPlugin.cpp - Remote Daily Ping Plugin ------------------------------=
//
//  PingPlugin Class:
//
//  This class is used to ping the Ping.MagicStats.com server once a day.
//  This allows user tracking and should be an optional component. 
//
//=---------------------------------------------------------------------------=
//  This file is copyright (c) 1997-2000 Chris Lattner
//=---------------------------------------------------------------------------=

#include "PingPlugin.h"
#include "Options.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
 
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif

INIT_PLUGIN(PingPlugin);

void PingPlugin::ResetState() {
  int Socket = EstablishConnection("Ping.MagicStats.com", 80);

  if (Socket == -1) {
    if (MSOptions::Debug)
      cout << "Error Establishing connection: " << ErrorMessage << endl;
    return;
  }

  String Message = "GET /?" + GetMessageToSend() + "\n";
  cout << "Saving day state... Socket #" << Socket << " MSG: " << Message << endl;
  write(Socket, Message, Message.Length());
  close(Socket);
}

int PingPlugin::EstablishConnection(const char *Host, unsigned short Port) {
  struct hostent *phe;
  struct sockaddr_in sin;
 
  memset(&sin, 0, sizeof(sin));
  sin.sin_family = AF_INET;
 
  sin.sin_port = htons(Port);
  
  /* Map the host name to an IP Address, allowing for dotted decimal */
  if ((phe = gethostbyname(Host)))
    memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
  else {
    sin.sin_addr.s_addr = inet_addr(Host);
    if (sin.sin_addr.s_addr == INADDR_NONE) {
      ErrorMessage = "Could not resolve host name!";
      return -1;
    }
  }

  int s = socket(PF_INET, SOCK_STREAM, 0);
  if (s < 0) {
    ErrorMessage = "Could not create socket!";
    return -1;
  }
 
  if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
    ErrorMessage = "Could not connect to remote host!";
    return -1;
  }
 
  return s;
}
