#!/usr/bin/perl 

# This script provides any easy to use interface to the various
# compile-time configuration options.

# declare some variables
use vars qw (%settings $window @options $argstring);

# load some perl modules
use Curses;
use PV;
use PVWindow; 
	
$settings{option_file} = "configure.options";
$settings{appname} = "XFMail";

&CreateWindow;
$argstring = &ProcessOptions;
&endwin();

print $argstring, "\n";

exit;


#######################################3
# Functions:

sub CreateWindow {
	my $text = <<END;
This tool allows you to easily select what options you would like to 
compile into $settings{appname}.
END
#
#Hit [TAB] to start configuring...

	$window = new PVWindow($text);
	$window->display;
	#$window->activate;
}

sub ProcessOptions {
	# go through configure options file

	my $i=0;

	my @label;

	open (OPTIONS, $settings{option_file}) || &{
		&endwin();
		die "Oh-oh: $!";
	};
	while (<OPTIONS>) {
		s/\r//g; # get rid of CR and CL
		next if (/^\#/);
		next if !(/::/);
		chomp;
		my ($name, $type, $arg, $description) = split ('::');

		$options[$i]{name} = $name;
		$options[$i]{type} = $type;
		$options[$i]{arg} = $arg;
		$options[$i]{description} = $description;

		my ($x1, $y1) = (2, $i+2);

		if ($type =~ /checkbox/i) {
			$options[$i]{elem} = new PV::Checkbox ($name . ':  ' . $description, $x1, $y1,0);
		}
		elsif ($type =~ /text/) {
			$options[$i]{elem} = new PV::Entryfield ($x1, $y1, 50, 0, $name, "");
		}
		$i++;
	}
	close (OPTIONS);

	# start dialog options...
	my @dialog = ("Title", 4, 4, 75, 22, 1, 1);

	my $donebutton = new PV::Pushbutton ("Done",27,9);
	for (my $a=0; $a<@options; $a++) {
		# add each checkbox into the dialog
		# NOTE: numbering of elements starts at 1, not 0!

		my $index = $a + 1; # offset 1 to make logic below clearer
	
		my $prev = $index - 1;
		$prev = 1 if ($prev < 1);
		my $next = $index + 1;

		$prev = $i if ($index == 1);

		$z = $i+1; # Done button

		push (@dialog, $options[$a]{elem},$prev,$next,$next,$prev,$z,$z,$z,$z);
	}
	
	# add Done button
	push (@dialog, $donebutton, $i,1,1,$i,1,1,1,0);

	# create dialog
	my $foo = new PV::Dialog(@dialog);

	# finally, display the dialog
	my @checkbox_values = $foo->activate;

	my $string = "";

	# process states
	for (my $b=0; $b<@options;$b++) {
		# checkboxes
		if ($options[$b]{type} =~ /checkbox/) {
			if ($options[$b]{elem}->stat) {
				$string .= " --" . $options[$b]{arg};
			}
		}

		# text entry fields
		if ($options[$b]{type} =~ /text/) {
			my $input = $options[$b]{elem}->stat;
			if ($input) {
				$string .= " --" . $options[$b]{arg} . '=' . $input;
			}
		}
	}

	return $string;
}
