/*
	Auther:		Satoshi Yasuda	7m3tjz/ad6gz
*/

#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<sys/socket.h>
#include	<netinet/in.h>
#include	<netinet/ip.h>
#include	"dsgwd_pi.h"

void	config(int argc, char **argv)
{
	char	buff[128];
	char	*delmi = "=\n\r\t\0";
	char	*pnt;
	FILE	*config_file;
	int	len;

	if (argc == 2)
	{
		config_file = fopen (argv[1], "r");
		if (!config_file)
		{
			printf ("config file not found (%s)\n", argv[1]);
			exit (1);
		}
	} 
	else
	{
		config_file = fopen ("/etc/dsgwd_pi.conf","r");
		if (!config_file)
		{
			printf ("config file not found (/etc/dsgwd_pi.conf)\n");
			exit (1);
		}
	}

	while (fgets (buff, 127, config_file))
	{
		if (buff[0] != '#')
		{
			pnt = strtok(buff, delmi);
			pnt = strtok(NULL,delmi);

			if (!memcmp (buff, "REPEATER_CALL", 13))
			{
                                memset (client_call, 0x20, 8);
				len = strlen(pnt);
				if (len > 8) len = 8;
                                memcpy (client_call, pnt, len);
			}
			else if (!memcmp (buff, "PASSWORD", 8))
			{
				memset (client_password, 0x00, 64);
				memcpy (client_password, pnt, strlen(pnt));
			}
                        else if (!memcmp (buff, "TRUST_DOMAIN_NAME", 17))
                        {
                                memset (TrustDomainName, 0x00, 128);
                                memcpy (TrustDomainName, pnt, strlen(pnt));
                        }
                        else if (!memcmp (buff, "TRUST_DB_DOMAIN_NAME", 20))
                        {
                                memset (TrustDbDomainName, 0x00, 128);
                                memcpy (TrustDbDomainName, pnt, strlen(pnt));
                        }
                        else if (!memcmp (buff, "REPEATER_MODE", 13))
                        {
                                if (memcmp (pnt, "YES", 3) == 0)
					repeater_mode = 1;
                        }
			else if (!memcmp (buff, "CMD_MODE", 8))
			{
				/* 0 stdin */
				/* 1 fifo  */
				cmdmode = atoi (pnt);
			}
			else if (!memcmp (buff, "PORT", 4))
			{
				client_port = atoi(pnt);
			}
                        else if (!memcmp (buff, "TRUST_PORT", 10))
                        {
                                trust_port = htons(atoi(pnt));
                        }
			else if (!memcmp (buff, "TRUST_DB_PORT", 13))
			{
				trust_db_port = htons(atoi(pnt));
			}
                        else if (!memcmp (buff, "NODE_ADAPTER_VENDOR_ID", 22))
                        {
                                NodeVendorID = atoi(pnt);
                        }
			else if (!memcmp (buff, "NODE_ADAPTER_PRODUCT_ID", 23))
                        {
                                NodeProductID = atoi(pnt);
                        }
		}
	}
	fclose (config_file);
}
