#! /usr/bin/perl
# Copyright 2000-2013 Double Precision, Inc.  See COPYING for
# distribution information.

use strict;
use warnings;
use Getopt::Long;

my $copy;

exit 1 unless GetOptions("copy" => \$copy );
$| = 1;

print "Checking for sysconftool: ";

my $aux_dir=".";
my $prefix="/usr/local";
my $datarootdir="${prefix}/share";

if (open(CONF, "configure.in") || open(CONF, "configure.ac"))
{
    my $l;

    while (defined ($l=<CONF>))
    {
	next unless $l =~ /AC_CONFIG_AUX_DIR[ \t]*\((.*)\)/;
	$aux_dir=$l;
	last;
    }
    close(CONF);
}

my $sysconftool="";

foreach ( ($aux_dir, ".", "..", "../.."))
{
	next unless -f "$_/sysconftool";

	$sysconftool="$_/sysconftool";
	print "$sysconftool\n";
	last;
}

unless ($sysconftool)
{
	system(($copy ? "cp -p":"ln -s") . " ${datarootdir}/sysconftool/sysconftool .") == 0
		|| die "$!\n";
	print "${datarootdir}/sysconftool/sysconftool\n";
}

print "Checking Makefile.am: ";

open (MAM, "+<Makefile.am") || die "Makefile.am: $!\n";

my $found=0;
my $l;

while (defined ($l=<MAM>))
{
	next unless $l =~ /^install-configure:/;
	$found=1;
	print "Ok\n";
	last;
}

unless ($found)
{
	seek(MAM, 0, 2);
	open(F, "${datarootdir}/sysconftool/sysconftoolize.am") || die "sysconftoolize.am: $!\n";
	print MAM <F>;
	close(F);
	print "appended install-configure\n";
}
close(MAM);

print "Don't forget to add AC_PROG_SYSCONFTOOL to configure.in\n";
