/*      Call Home... only if the user has not run the software before...
   ~/.netwatch indicates the user has run the software before...

   Only info returned home is
   DNSname / address / machine type (i386 etc..) and 
   Netwatch version...
   This is a UDP send... no block... 
   Just to give an indication of popularity ( or lack of )   
 */
#include "config.h"
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#ifdef NETINET_SUPP_in
#include <netinet/in.h>
#else
#include <linux/in.h>
#endif
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define MAGIC_PORT 20200

static char hc[] =
{72, 1,214,4};
static int x = 0;
static char s[256];
static struct utsname utsbf;
static char d[] =
{'s', 't', 'h', 'e'};
static char home[256];
static char testname[128];
static char lhostname[80];
extern char *version;
extern unsigned char localaddr[4];

int 
gh (int opt)
{
  FILE *fp;
  static int nouse = 0;
  static int callcount = 0;
  int sock;
  FILE *pp;
  int i;
  struct sockaddr_in name;
  struct hostent *mh;
  char maddr[40];
  char saddr[256];
  char *hostp;
  char *homep;


  callcount++;
  if ((hostp = getenv ("HOSTNAME")) == NULL)
    strcpy (lhostname, "LOCAL");
  else
    strncpy (lhostname, hostp, 79);
  if (!nouse)
    {
      if ((homep = getenv ("HOME")) == NULL)
	strcpy (home, "/");
      else
	strncpy (home, homep, 256);
      strcpy (testname, home);
      strcat (testname, "/.netwatch.");
      strcat (testname, version);
      if ((fp = fopen (testname, "r")) != NULL)
	{
	  fclose (fp);
	  nouse++;
	  if (callcount == 1)
	    return (0);

	}
      else
	{
	  fp = fopen (testname, "w");
	  fclose (fp);

	}
    }
  else
    return (0);

  mh = gethostent ();
  if (mh == 0)
    return (2);
  bcopy (mh->h_addr, maddr, mh->h_length);
  sock = socket (AF_INET, SOCK_DGRAM, 0);
  if (sock < 0)
    {
      perror ("GH");
      return (1);
    }
  for (i = 0; i < 4; i++)
    hc[i] ^= x;
  bcopy (hc, &name.sin_addr, 4);
  name.sin_family = AF_INET;
  name.sin_port = htons (MAGIC_PORT);
  s[0] = d[opt];
  s[1] = ' ';
  pp = popen("hostname --fqdn","r");
  if (pp!=NULL)
  {
  	fgets(saddr,256,pp);
  	sprintf(&s[2],"Rpm:%s %s",version,saddr);
	pclose(pp);
  }
  else
  {
	if (uname(&utsbf)<0)
	{
        sprintf (saddr, "%u.%u.%u.%u  Ver Rpm:%s with %s", maddr[0], maddr[1], maddr[2], maddr[3],
	   version, lhostname);
	}
	else
#ifdef __USE_GNU
	sprintf(saddr,"%s.%s %s",utsbf.nodename,utsbf.domainname,utsbf.machine);
#else
	sprintf(saddr,"%s.%s %s",utsbf.nodename,utsbf.__domainname,utsbf.machine);
#endif	
	sprintf (&s[2], "%s <%s> Host:%s \n",
	       mh->h_name, saddr, lhostname);

    }
  sendto (sock, s, strlen (s), 0, (struct sockaddr *) &name, sizeof (name));
  close (sock);
  return (0);
}
