#!/usr/bin/perl -w
# -*- cperl -*-

use strict;

use File::Basename;
use File::Path;
use File::stat;
use FileHandle;
use FindBin;
use Getopt::Long;


########################################################################
#
#  command line processing
#


my $name;
my $sparsity;
my $reporting_url;
my $installdir;
my $template = "$FindBin::Bin/application.schemas.in";

sub usage () {
  die <<"EOT";
Usage: $0 [options]

  --name=NAME
  --sparsity=NUM
  --reporting-url=URL
  --install=PATH
  --template=FILE

All options are required except for \"--template\".
EOT
}

my $result = GetOptions ('name=s' => \$name,
			 'sparsity=i' => \$sparsity,
			 'reporting-url=s' => \$reporting_url,
			 'install=s' => \$installdir,
			 'template=s' => \$template);

usage unless $result;
usage unless $name;
usage unless $sparsity;
usage unless $reporting_url;
usage unless $installdir;

usage if @ARGV;


########################################################################
#
#  helper subroutines
#


sub installdir ($) {
  mkpath dirname $_[0];
}


sub instantiate ($$%) {
  my ($input, $output, %substitutions) = @_;
  my $infile = new FileHandle $input, 'r' or die "cannot read $input: $!\n";
  my $outfile = new FileHandle $output, 'w' or die "cannot write $output: $!\n";

  while (<$infile>) {
    s/@([[:word:]]+)@/$substitutions{$1}/g;
    $outfile->print($_);
  }
}


########################################################################
#
#  main activity
#


my $schemas = "$installdir/etc/gconf/schemas/sampler-$name.schemas";
installdir $schemas;
instantiate($template, $schemas,
	    'name' => $name,
	    'sparsity' => $sparsity,
	    'reporting_url' => $reporting_url);
chmod(0644, $schemas) == 1 or die "cannot chmod $schemas: $!\n";
