/*
 * Velleman K8048 Programmer for FreeBSD and others.
 *
 * Copyright (c) 2005-2007 Darron Broad
 * All rights reserved.
 *
 * Licensed under the terms of the BSD license, see file LICENSE
 * for details.
 *
 * $Id: dotconf.c,v 1.13 2008/09/19 04:42:20 darron Exp $
 */

#include "k8048.h"

/******************************************************************************
 * DOT CONFIG FUNCTIONS
 *****************************************************************************/

void
getconf(struct k8048 *k)
{
    char line[STRLEN], *homedir, *username;
    FILE *f1;

    /* clear config */
    bzero(k, sizeof(struct k8048));

    /* defaults */
    strncpy(k->device, SERIAL_DEVICE, STRMAX);
    k->flags = K8048;
    k->sleep_short= 1;
    k->sleep_long= 1;
    k->debug_level= 0;

    /* default to current working directory */
    snprintf(k->dotfile, STRLEN, "%s/%s", getcwd(line, STRLEN), DOTFILENAME);
    if(access(k->dotfile, R_OK) < 0)
    {
        /* try home dir */
        homedir= getenv("HOME");
        if(homedir!=NULL)
            snprintf(k->dotfile, STRLEN, "%s/%s", homedir, DOTFILENAME);
        else
        {
            /* try default home dir */
            username= getenv("USER");
            if(username!=NULL)
                snprintf(k->dotfile, STRLEN, "/home/%s/%s", username, DOTFILENAME);
        }
    }

    /* load dotfile if present */
    f1= fopen(k->dotfile, "rb");
    if(f1!=NULL)
    {
        while( fgets(line, STRLEN, f1) != NULL)
        {
            line[ strlen(line) - 1]= '\0';

            if(mystrcasestr(line, "DEVICE=")==line)
                strncpy(k->device, &line[7], STRMAX);

            else if(mystrcasestr(line, "BITRULES=")==line)
                k->flags= strtoul(&line[9], NULL, 0);
            
	    else if(mystrcasestr(line, "SLEEP_SHORT=")==line)
                k->sleep_short= strtoul(&line[12], NULL, 0);

	    else if(mystrcasestr(line, "SLEEP_LONG=")==line)
                k->sleep_long= strtoul(&line[11], NULL, 0);
	    
	    else if(mystrcasestr(line, "DEBUG_LEVEL=")==line)
                k->debug_level= strtoul(&line[12], NULL, 0);
        }
        fclose(f1);
    }
    else /* Use defaults */
    {
        snprintf(k->dotfile, STRLEN, "Default (override in %s)", DOTFILENAME);
    }
}
