#!/usr/bin/env perl
# the above line will use any perl that is in your PATH. You might want to
# replace it by #!/usr/bin/perl or similar if this does not work for you.

use strict;
use warnings;
use File::Copy;
use Getopt::Long;

# find sxw2txt and other scripts in current dir, if scripts not installed yet
$ENV{PATH} .= ':.';

use vars qw($opt_help $opt_prefix $opt_nomake $opt_shell);

Getopt::Long::Configure("prefix_pattern=--");
my $result = GetOptions('help+', 'prefix=s', 'shell=s', 'nomake+');
if ( $ARGV[0] or not $result or $opt_help) {
	print << 'EOF';
Usage: configure [options]
Options:
 --help			print this message
 --shell=<filename>	specify an alternative shell path (zsh/bash) to use
 --nomake		do not generate a Makefile
Directory and file names:
 --prefix=PREFIX	install lesspipe.sh in PREFIX/bin (/usr/local)

configure generates by default a Makefile
EOF
	$opt_help ? exit 0 : exit 1;
}

my $prefix = $opt_prefix || $ENV{PREFIX} || '/usr/local';

# remove trailing slash and trailing bin directory
print "removed trailing /bin dir from prefix\n" if $prefix =~ m|/bin/?$|;
$prefix =~ s|(/bin)?/?$||;
if ( $opt_shell and -f $opt_shell and $opt_shell =~ /^\// ) {
	# do nothing
} elsif ( $opt_shell) {
	print "unuseable shell $opt_shell: not executable or no absolute path\n";
	exit 1;
}

# gererate Makefile
my @bad = ();
my $shell = check_shell_vers();
my $no_bash = (grep {/bash/} @bad);
my $no_zsh = (grep {/zsh/} @bad);
my $bash_complete_dir = "$prefix/share/bash-completion";
# override prefix and use the system defined directory if known
if (`pkg-config --version 2>/dev/null`) {
	$bash_complete_dir = `pkg-config --variable=completionsdir bash-completion`;
	chomp $bash_complete_dir;
}

if ( ! $opt_nomake ) {
	open OUT, ">Makefile";
	while (<DATA>) {
		next if /bash_complete_dir/ and $no_bash;
		next if /zsh\/site-functions/ and $no_zsh;
		s/opt_prefix/$prefix/;
		if ($bash_complete_dir and ! $opt_prefix) {
			s/mkdir.*bash-completion.*/mkdir -p $bash_complete_dir/;
			s/cp.*bash-completion.*/cp .\/less_completion $bash_complete_dir/;
		}
		print OUT;
	}
	close OUT;
}
if (! $no_bash) {
	print "installing bash completion in $bash_complete_dir\nIn bash, please preload the completion, dynamic invocation does not work\n. $bash_complete_dir/less_completion\nOr consider installing the file less_completion in /etc/bashcompletion.d\n";
}
for my $file ("lesspipe.sh", "lesscomplete") {
	open F, $file;
	my $line1 = <F>;
	next if $line1 =~ /^$shell$/;
	local $/;
	my $in = <F>;
	print "generating new $file using '$shell' as first line\n";
	copy $file, "$file.old";
	open OUT, ">$file";
	print OUT "$shell\n";
	print OUT $in;
	close OUT;
	close F;
	chmod 0755, $file
}
exit 0;

sub check_shell_vers {
	# define useable shells, the order is important !
	my @shells = qw( /bin/bash /bin/zsh /bin/sh);
	@shells = ( $opt_shell ) if $opt_shell;
	my $selected_shell = '';
	my $shellcmd = '';
	for my $shell ( @shells ) {
		# get the basename of the shell and shell options
		my ($path, $name, $opt);
		if ( $shell =~ /(.*)\/([^\/]+)(\s.*)$/ ) {
			($path, $name, $opt) = ($1, $2, $3);
		} else {
			($path, $name, $opt) = ($1, $2, "") if $shell =~ /(.*)\/([^\/]+)\s*$/;
		}
		# do we have the shell in the PATH
		my $versstr = uc $name.'_VERSION';
		$versstr = 'BASH_VERSION' if $name eq 'sh';
		my @where = grep { -x $_."/$name" } split ':', $ENV{PATH};
		$where[0] = $path if -x $path.'/'.$name;
		my $file = $where[0].'/'.$name if $where[0];
		if ( ! $where[0] or ! -x $file ) {
			print "$name not found in the PATH, continuing\n";
			push	@bad, $shell;
			next;
		}
		# get the shell version
		my $v = `$file -c \'echo \$$versstr\'`;
		chomp $v;
		$v = $1 if $v =~ /(\d+\.\d+)/;
		### print "$file $v found in the PATH\n";
		if ( $name eq 'bash' or $name eq 'sh' ) {
			if ( ! $v or $v < 5 ) {
				push @bad, $shell;
				next;
			}
		}
		$selected_shell = $name if ! $selected_shell;
		$shellcmd = "$file$opt" if ! $shellcmd;
	}
	if ( !$selected_shell ) {
		print "Sorry, no useable shell found, the following were tried:\n@bad\n";
		print "You could run configure --shell=<abs_filename> to retry\n";
		exit 1;
	}
	return "#!/usr/bin/env $selected_shell";
}
__END__
# This is a generated file, do not edit it. Use configure to modify it
PREFIX = opt_prefix

.PHONY: install

all:
	./configure --prefix=$(PREFIX)
test:
	./test.pl
install:
	mkdir -p $(DESTDIR)$(PREFIX)/bin
	mkdir -p $(DESTDIR)$(PREFIX)/share/man/man1
	mkdir -p $(DESTDIR)$(PREFIX)/share/zsh/site-functions
	mkdir -p $(DESTDIR)$(PREFIX)/share/bash-completion/
	cp ./code2color ./sxw2txt ./archive_color ./lesspipe.sh ./vimcolor ./lesscomplete $(DESTDIR)$(PREFIX)/bin
	cp ./lesspipe.1 $(DESTDIR)$(PREFIX)/share/man/man1
	cp ./less_completion $(DESTDIR)$(PREFIX)/share/bash-completion/
	cp ./_less $(DESTDIR)$(PREFIX)/share/zsh/site-functions
	chmod 0755 $(DESTDIR)$(PREFIX)/bin/lesspipe.sh
	chmod 0755 $(DESTDIR)$(PREFIX)/bin/sxw2txt
	chmod 0755 $(DESTDIR)$(PREFIX)/bin/code2color
	chmod 0755 $(DESTDIR)$(PREFIX)/bin/archive_color
	chmod 0755 $(DESTDIR)$(PREFIX)/bin/vimcolor
	chmod 0755 $(DESTDIR)$(PREFIX)/bin/lesscomplete
clean:
	mv Makefile Makefile.old
