#!/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;

# 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);

use Getopt::Long;
Getopt::Long::Configure("prefix_pattern=--");
my $result = GetOptions
    qw(help+ prefix=s shell=s yes+ default+ ask+ nomake+ fixed+);
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.sh in PREFIX/bin (/usr/local)

configure generates by default a Makefile
EOF
  exit ! $opt_help ? 1 : 0;
}
$opt_prefix ||= '/usr/local';
# remove trailing slash and trailing bin directory
print "removed trailing /bin dir from prefix\n" if $opt_prefix =~ m|/bin/?$|;
$opt_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;
}

if ( ! $opt_nomake ) {
  open OUT, ">Makefile";
  print OUT << "EOF";
# 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
	cp ./code2color ./sxw2txt ./archive_color ./lesspipe.sh ./vimcolor \$(DESTDIR)\$(PREFIX)/bin
	cp ./lesspipe.1 \$(DESTDIR)\$(PREFIX)/share/man/man1
	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
clean:
	mv Makefile Makefile.old
EOF
  close OUT;
}

my $shell = check_shell_vers();
open F, "lesspipe.sh";
{
	my $line1 = <F>;
	exit if $line1 =~ /^$shell$/;
	local $/;
	my $in = <F>;
	print "generating new lesspipe.sh using '$shell' as first line\n";
	copy "lesspipe.sh", "lesspipe.sh.old";
	open OUT, ">lesspipe.sh";
	print OUT "$shell\n";
	print OUT $in;
	close OUT;
}
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 @bad = ();
  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\n";
      push  @bad, $shell;
      next;
    }
    # get the shell version
    my $v = `$file -c \'echo \$$versstr\'`;
    chomp $v;
    ###    print "$file $v found in the PATH\n";
    if ( $name eq 'bash' or $name eq 'sh' ) {
      my $tst = `$file -c \'if [[ -n 1 && -n 2 ]];then true;fi 2>&1\'`;
      if ( $tst ) {
	push @bad, $shell;
	next;
      }
    }
    $selected_shell = $name if ! $selected_shell;
    $shellcmd = "$file$opt" if ! $shellcmd;
  }
  if ( !$selected_shell ) {
    print "Sorry, no useable shell found\n", @bad;
    print "You could run configure --shell=<abs_filename> to retry\n";
    exit 1;
  }
  return "#!$shellcmd";
}
