/*
 * Copyright 2002 Sun Microsystems, Inc.  All rights reserved.
 *
 * Use is subject to the GNU General Public License, Version 2,
 * June 1991, which is contained in the read-me file named
 * "README_GNU_GPL." This program is free software; you can
 * redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your
 * option) any later version. This library is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA  02111-1307  USA.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <getopt.h>
#include "lcd.h"
#include "lcdutils.h"

/* FIXME - timeout needed */
#define OPTIONS "sh1:i:"

int main(int argc, char **argv) {
	void *lcd;
	int one, two, three, four, c, silent = 0;
	char *line, ipstr[17], ipaddr[17];
	
	extern char *optarg;
	extern int opterr;
	
	opterr = 0; /* make getopt quiet */ 
	
	lcd_setlocale();
	
	strcpy(ipaddr, "000.000.000.000");
	strcpy(ipstr, _("PRIMARY IP ADDR:"));
	
	/* we silently ignore bad options. so, only -h returns usage. */
	while ((c = getopt(argc, argv, OPTIONS)) != EOF) {
		switch (c) {
			case 's':
				silent++;
				break;
			
			case '1':
				strncpy(ipstr, optarg, sizeof(ipstr) - 1);
				break;
			
			case 'i':
				strncpy(ipaddr, optarg, sizeof(ipaddr) - 1);
				lcd_rev_format(ipaddr);
				break;
			
			case 'h':
				printf(_("Usage: %s [-1 <line text>] [-i <ip addr>]\n"),argv[0]);
				exit(0);
				break;
			
			default:
				break;
		}
	}
	
	if (!silent && (lcd_lock() < 0)) {
		printf(_("LCD in use... try again later\n"));
		exit(0);
	}
	
	if ((lcd = lcd_open(O_RDWR)) == NULL) {
		printf(_("LCD is not present\n"));
		exit(0);
	}
	
	lcd_reset(lcd);
	lcd_set(lcd, LCD_Blink_Off);
	lcd_wait_no_button(lcd);
	lcd_write(lcd, ipstr, ipaddr);
	lcd_setcursorpos(lcd, 0x40);
	lcd_wait_no_button(lcd);
	lcd_netbutton(lcd);
	
	lcd_getdisplay(lcd, NULL, &line, NULL);
	strncpy( ipaddr, line, 15 );
	lcd_close(lcd);
	if (!silent)
		lcd_unlock();
	
	sscanf(ipaddr,"%d.%d.%d.%d", &one, &two, &three, &four);
	if (one > 255) one = 0;
	if (two > 255) two = 0;
	if (three > 255) three = 0;
	if (four > 255) four = 0;
	printf("%d.%d.%d.%d",one,two,three,four);
	exit(0);
}


