/*
 * hostname	This file contains an implementation of the command
 *		that either displays or sets a system's host (and/or
 *		domain) name.  If no name is given on the command
 *		line, this program will display the current hostname
 *		or domainname.  Othwerwise, it will set a new value.
 *
 * Usage:	hostname [-f] [name]
 *		domainname [name]
 *
 * Version:	@(#)hostname.c	2.20	10/02/93
 *
 * Author:	Fred N. van Kempen, <waltje@uwalt.nl.mugnet.org>
 */
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include "support.h"
#include "pathnames.h"
#include "version.h"


char *Release = RELEASE,
     *Version = "@(#) hostname 2.20 (10/02/93)";


static void
usage1(void)
{
  fprintf(stderr, "Usage: hostname [-f] [name]\n");
  exit(-1);
}


static void
usage2(void)
{
  fprintf(stderr, "Usage: domainname [name]\n");
  exit(-1);
}


int
main(int argc, char **argv)
{
  struct sockaddr sa;
  char name[128], *sp;
  struct aftype *ap;
  int c, opt_f, setdomain;
  extern int getopt(), optind, opterr;

  if ((sp = strrchr(argv[0], '/')) != NULL) sp++;
    else sp = argv[0];
  setdomain = (strcmp(sp, "domainname") == 0);

  /* This is a kludge.  Really... */
  if ((ap = get_aftype("inet")) == NULL) {
	fprintf(stderr, "hostname: address family \"inet\" unknown!\n");
	exit(1);
  }

  /* Fetch the command-line arguments. */
  opterr = 0;
  opt_f = 0;
  while ((c = getopt(argc, argv, "f")) != EOF) switch(c) {
	case 'f':
		opt_f = 1;
		if (setdomain) usage2();
		break;

	default:
		if (setdomain) usage2();
		  else usage1();
  }

  /* Do we have to SHOW the current setting? */
  if (optind == argc) {
	if (setdomain) {
		if (getdomainname(name, 128) < 0) {
			perror("getdomainname");
			exit(-1);
		}
	} else {
		if (gethostname(name, 128) < 0) {
			perror("gethostname");
			exit(-1);
		}
	}
	printf("%s\n", name);
	exit(0);
  }

  /* No.  We have to (re-)set a name. */
  strncpy(name, argv[optind], 128);
  if (setdomain) {
	if (setdomainname(name, strlen(name)) < 0) {
		perror("setdomainname");
		exit(-1);
	}
  } else {
	if (opt_f) (void) ap->input(name, &sa);
	if (sethostname(name, strlen(name)) < 0) {
		perror("sethostname");
		exit(-1);
	}
  }

  return(0);
}
