#  -*- Perl -*-
eval "exec perl -S $0 $*"
    if $running_under_some_shell;

#####  Edit these destination directories to your liking
#  Destination for the scripts
$scripts_dest   =  "/sbin";

#  Destination for the configuration files (Config.pl and Bootdisk_Contents)
$config_dest    =  "/etc/yard";

#  Destination for the library files (in Replacements/ and extras/).
#  These are under /etc instead of /usr/lib because they're configurable.
$lib_dest       =  "/etc/yard";


##############################################################################
#####  Nothing below this line should need changing
##############################################################################
require 5.002;			# We need 5.002 for all scripts
use POSIX qw(tmpnam);
use Config;
use English;
use FileHandle;

if ($Config{'osname'} !~/linux/i) {	# Just to be careful
  die "You're not running Linux?!\n";
}

test_cp();
test_lstat();

chomp($yard_version= `cat VERSION`);

@directories = qw(scripts_dest lib_dest config_dest);

@output_scripts = qw(scripts/check_root_fs
		     scripts/create_loopback_file
		     scripts/create_replacements
		     scripts/identify_bootdisk 
		     scripts/make_root_fs
		     scripts/write_rescue_disk);

@output_others = qw(Makefile doc/Makefile extras/Makefile scripts/Makefile
		    Config.pl Bootdisk_Contents 
		    yardconfig.pm);


@necessary_progs = qw(perl make ldd ldconfig chroot install sync mount
		      umount rm cp dd mke2fs rdev gzip gunzip uname
		      mkdir mv);

@optional_progs = qw(lilo tar as86 ld86 
		     latex dvips sgml2latex sgml2txt sgml2info 
		     sgml2html install-info objcopy);

@misc_substitutions = qw(configure_input yard_version);

	
@pathdirs = split(':', $ENV{'PATH'});


##############################################################################
#####  Find and record locations of important programs
##############################################################################
foreach $prog (@necessary_progs) { 
    record_loc($prog, find_file_in_path($prog, 1));
}
foreach $prog (@optional_progs)  { 
    record_loc($prog, find_file_in_path($prog, 0));
}

if (!defined($loc{'objcopy'})) {
    print "Warning: objcopy not found -- unable to strip binaries.\n";
}


##############################################################################
#####  Build substitutions
##############################################################################
$substs = "";
foreach $prog (@necessary_progs, @optional_progs) {
    $substs .= "s|\\\@${prog}\\\@|$loc{$prog}|gi;\n"; }
foreach $var (@directories, @misc_substitutions) {
    $substs .= "s|\\\@${var}\\\@|\$$var|gi;\n"}
    
#####  Substitute into scripts
foreach $script (@output_scripts, @output_others) {
    print "Creating $script\n";
    $source = "${script}.in";
    if (!open(SOURCE, $source))  { print "$source: $!\n"; next };
    if (!open(DEST, ">$script")) { print "Writing $dest: $!\n"; next };
    $configure_input = "This script created automatically from $source";
    while (<SOURCE>) {
	eval $substs if /\@/;
	print DEST;
    }
    close(DEST) or print "Closing $script: $!";
    close(SOURCE) or print "Closing $source: $!";
}

#####  Make the scripts executable
chmod(0755, @output_scripts);

print "Done.\n";
exit;

##############################################################################

sub find_file_in_path {
    my($file, $necessary) = @_;
    print "Looking for $file...";

    if ($file =~ m|/|) {
	#####  Absolute
	if (-e $file) {
	    print "Found it\n";
	    return($file);
	}
	
    } else {
	#####  Relative filename, search for it
	foreach $path (@pathdirs) {
	    $abs_file = "$path/$file";
	    if (-e $abs_file) {
		print "$abs_file\n";
		return $abs_file;
	    }
	}
    }

    print "NOT FOUND\n";
    if ($necessary) {
	print "$file is necessary, cannot continue.\n",
	      "Install it or fix your PATH so I can find it.\n";
	die("\n");
    }
    undef
}
 

sub record_loc {
    my($prog, $loc) = @_;
    $loc{$prog} = defined($loc) ? $loc : "";
}

	
#####  Check the cp command.  It's broken in fileutils 3.13.
sub test_cp {
    print  "Checking your version of cp...";
    my($dirname)  = tmpnam();
    my($filename) = tmpnam();
    
    my($setup_problem) = system("mkdir $dirname") ||
	                 system("touch $filename");
    if (!$setup_problem) {
	if (system("cp --parents -R $filename $dirname")) {
	    
	    print "\n***** Your cp command is broken and can't be used with Yard.\n";
	    print "***** Read the file doc/Broken_cp which explains",
	          " how to fix it.\n";
	    exit;
	    
	} else {
	    print "OK\n";
	    system("rm -rf $dirname $filename");
	}
    } else {
	die "Problem in setting up test_cp in /tmp !!";
    }
}


sub test_lstat {
  #  Create a temp file
  my($file) = tmpnam();
  open(X, ">$file") or die "Can't create $file!\n";
  close(X);
  #  Try to set up a symlink to it
  my($link) = tmpnam();
  if (!symlink($file, $link)) {
    print "Can't symlink $link -> $file ?!?!\n";
    print "Something's wrong!\n";
    unlink($file);
    die;

  } elsif (!-l $link) {		#  Test the -l operator on the link
    print "ERROR: Your perl can't recognize symlinks with -l\n",
          "\$Config{\"d_lstat\"} = \"$Config{'d_lstat'}\"\n",
          "Yard may not work properly.\n",
          "See doc/Broken_lstat for further information.\n";
    unlink($file, $link);
    exit;

  } else {			#  Probably unnecessary, but test lstat too.
    my($stat) = join(',', stat($link));
    my($lstat) = join(',', lstat($link));

    if ($stat eq $lstat) {
      print "ERROR: lstat is broken in this perl\n",
            "(both stat and lstat returned the same info on a link)\n",
            "\$Config{\"d_lstat\"} = \"$Config{'d_lstat'}\"\n",
            "Yard may not work properly.\n",
            "See doc/Broken_lstat for further information.\n";
      unlink($file, $link);
      exit;
      
    } else {
      print "Both lstat and -l seem to work -- good\n";
      unlink($file, $link);
    }
  }
}
