#!/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_bindir $opt_mandir $opt_zsh_completion_dir $opt_bash_completion_dir $opt_nomake $opt_shell);

Getopt::Long::Configure("prefix_pattern=--");
my $result = GetOptions('help+', 'prefix=s', 'bindir=s', 'mandir=s', 'bash-completion-dir=s', 'zsh-completion-dir=s', 'shell=s', 'nomake+');
if ( $ARGV[0] or ! $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 stuff in PREFIX (/usr/local)
 --bindir=BINDIR	install lesspipe.sh in BINDIR (PREFIX/bin)
 --mandir=MANDIR	install man pages in in MANDIR (PREFIX/share/man/man1)
 --bash-completion-dir=DIR	install bash auto-completion file in in DIR (pkg-config --variable=completionsdir bash-completion)
 --zsh-completion-dir=DIR	install zsh auto-completion file in in DIR (PREFIX/share/zsh/site-functions)

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

my $prefix = $opt_prefix || $ENV{PREFIX} || '/usr/local';
my $bindir = $opt_bindir || $ENV{BINDIR} || "$prefix/bin";
my $mandir = $opt_mandir || $ENV{MANDIR} || "$prefix/share/man/man1";
my $bash_complete_dir = $opt_bash_completion_dir || "$prefix/share/bash-completion";
# override prefix and use the system defined directory if known
if ( ! $opt_bash_completion_dir && `pkg-config --version 2>/dev/null`) {
	$bash_complete_dir = `pkg-config --variable=completionsdir bash-completion`;
	chomp $bash_complete_dir;
}
my $zsh_complete_dir = $opt_zsh_completion_dir || "$prefix/share/zsh/site-functions";

# remove trailing slash and trailing bin directory
if ($prefix =~ m|/bin/?$|) {
	print "removed trailing /bin dir from prefix\n";
	$prefix =~ s|(/.+)?/?$||;
}
if ( $opt_shell and -f $opt_shell and $opt_shell =~ /^\// ) {
	# do nothing
} elsif ( $opt_shell) {
	print "unusable 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);

if ( ! $opt_nomake ) {
	open OUT, ">Makefile";
	while (<DATA>) {
		next if /BASH_COMPLETION/ and $no_bash;
		next if /ZSH_COMPLETION/ and $no_zsh;
		s/opt_prefix/$prefix/;
		s/opt_bindir/$bindir/;
		s/opt_mandir/$mandir/;
		s/bash_complete_dir/$bash_complete_dir/;
		s/zsh_complete_dir/$zsh_complete_dir/;
		print OUT;
	}
	close OUT;
	print "A Makefile has been generated\n\tprefix $prefix\n\tbindir $bindir\n",
		"\tmandir $mandir\n\tbash_complete_dir $bash_complete_dir\n",
		"\tzsh_complete_dir  $zsh_complete_dir\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 usable 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 usable 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
BINDIR = opt_bindir
MANDIR = opt_mandir
BASH_COMPLETION = bash_complete_dir
ZSH_COMPLETION = zsh_complete_dir

.PHONY: install

all:
	$(info "make install" will install lesspipe.sh in $(PREFIX))
test:
	./test.pl
install:
	mkdir -p $(DESTDIR)$(BINDIR)
	mkdir -p $(DESTDIR)$(MANDIR)
	mkdir -p $(DESTDIR)$(ZSH_COMPLETION)
	mkdir -p $(DESTDIR)$(BASH_COMPLETION)
	cp ./code2color ./sxw2txt ./archive_color ./lesspipe.sh ./vimcolor ./lesscomplete $(DESTDIR)$(BINDIR)
	cp ./lesspipe.1 $(DESTDIR)$(MANDIR)
	sed -e "s@__BINDIR__@$(BINDIR)@" ./bash_completion > $(DESTDIR)$(BASH_COMPLETION)/less
	sed -e "s@__BINDIR__@$(BINDIR)@" ./zsh_completion > $(DESTDIR)$(ZSH_COMPLETION)/_less
	chmod 0755 $(DESTDIR)$(BINDIR)/lesspipe.sh
	chmod 0755 $(DESTDIR)$(BINDIR)/sxw2txt
	chmod 0755 $(DESTDIR)$(BINDIR)/code2color
	chmod 0755 $(DESTDIR)$(BINDIR)/archive_color
	chmod 0755 $(DESTDIR)$(BINDIR)/vimcolor
	chmod 0755 $(DESTDIR)$(BINDIR)/lesscomplete
clean:
	mv Makefile Makefile.old
