/*
 *  Copyright (C) 1995, 1996  Karl-Johan Johnsson.
 */

#include "global.h"
#include "domain.h"
#include "resource.h"
#include "widgets.h"
#include <pwd.h>

#include "sysdeps.h"

static void fix_domain_name(void)
{
#ifdef DOMAIN_FILE
    char	*fn = DOMAIN_FILE;
    FILE	*fp;

    fp = fopen(fn, "r");
    if (fp) {
	char	 buffer[256];

	if (fgets(buffer, sizeof buffer - 1, fp)) {
	    char	*c = strchr(buffer, '\n');

	    if (c)
		*c = '\0';
	    if (strchr(buffer, '.'))
		global.domain_name = XtNewString(buffer);
	}

	fclose(fp);
    }
#endif

#ifdef DOMAIN_NAME
    if (!global.domain_name) {
	char	*dn = DOMAIN_NAME;

	if (strchr(dn, '.'))
	    global.domain_name = XtNewString(dn);
    }
#endif

    if (!global.domain_name)
	global.domain_name = get_mailhostname();
}

static void fix_user_id(void)
{
    struct passwd	*pw;

    pw = getpwuid(getuid());

    if (pw) {
	if (pw->pw_name)
	    global.user_id = XtNewString(pw->pw_name);

	if (!getenv("NAME") && pw->pw_gecos) {
	    char	*c = strchr(pw->pw_gecos, ',');

	    if (c)
		*c = '\0';
	    res_set_pw_name(pw->pw_gecos);
	}
    }
}

void fix_domain_stuff()
{
    fix_domain_name();
    fix_user_id();

    if (!global.domain_name)
	fputs("knews: Couldn't determine domain name. "
	      "Posting will not be possible.\n", stderr);
    else if (!global.user_id)
	fputs("knews: Couldn't determain user id. "
	      "Posting will not be possible.\n", stderr);

    if (!global.mail_name || global.mail_name[0] == ' ')
	global.mail_name = global.user_id;
}
