#!/usr/bin/perl

# Read the user requirement file from the command line:
$user_req = shift;
if ($user_req eq "") {
  die "usage: configure user_req.lp";
}
# infrastructure for temporary files, from PerlFAQ.
use File::Temp qw/ tempfile tempdir /;

sub create_tmp_file_name {
  ($fh, $filename) = tempfile();
  close $fh;
  push @unlink_on_exit, $filename;
  $filename;
}

# define the used binaries and files:
$lparse = "lparse -Wn";
$smodels = "smodels";
$configuration_model = "simple_configuration_model.lp";
$package_data = "example1.lp";
$diagnostic_model = "simple_diagnostic_model.lp";
$conf_file = create_tmp_file_name();
$diag_file = create_tmp_file_name();

print "User requirements:\n";
open IN, "$user_req" or die "can't open '$user_req'\n";
while (<IN>) {
  print;
}
close IN;
print "\n";
# Compute the actual configurations:
print "Configuring...\n";
`$lparse $user_req $configuration_model $package_data | smodels 0 > $conf_file`;

# read the results:
open IN, "$conf_file" or die "cannot open temporary file";
while (<IN>) {
  if (/Answer/) {
	# read one configuration
	$_ = <IN>;
    @atoms = split;
    shift @atoms;
    shift @atoms;
	undef @configuration;
    foreach $atom (@atoms) {
	  if ($atom =~ /^in/) {
		push @configuration, $atom;
      }
    }
	$confno++;
	print "Configuration $confno:\n";
	foreach $atom (sort @configuration) {
	  print "$atom\n";
	}
	print "\n";
  }
}
close IN;

if ($confno == 0) {
  print "No configuration found\n";
  print "Diagnosis:\n";
  # contradictionary, compute explanation:
  `$lparse $user_req $diagnostic_model $package_data | smodels > $diag_file`;
  open IN, "$diag_file";
  while (<IN>) {
	if (/Answer/) {
	  # read one configuration
	  $_ = <IN>;
	  @atoms = split;
	  shift @atoms;
	  shift @atoms;
	  undef @configuration;
	  foreach $atom (@atoms) {
		print "$atom\n";
	  }
	}
  }
}
