#!./perl

use strict;
use Config;
BEGIN {
    require "./subst.pm";
    require "./Config.pm";
    Envy::Config->import(qw($prefix $init_env $default_path $envy $default_startup));
}
use IO::File;

sub do_init_env {
    my ($file) = @_;
    my $str='';
    if ($file eq 'login.IN') {
	for my $k (sort keys %$init_env) {
	    my $v=$init_env->{$k};
	    $str .= "setenv $k $v\n";
	}
    } else {
	for my $k (sort keys %$init_env) {
	    my $v=$init_env->{$k};
	    $str .= "$k=$v; export $k\n";
	}
    }
    $str;
}

# This maps symlinks from $ETOP/etc/login/ to $HOME/.
my $symlink = {
	       'dot.profile' => ['.profile', '.zprofile', '.bash_profile'],
	       'dot.shrc' => ['.shrc', '.zshrc', '.bashrc'],
	       'dot.login' => ['.login'],
	       'dot.cshrc' => ['.cshrc'],
	       'dot.dtprofile' => ['.dtprofile'],
	      };

my $symlink_str;
while (my($k,$v) = each %$symlink) {
    for my $to (@$v) {
	$symlink_str .= 'safe_symlink $ETOP/etc/login/'.$k.' $HOME/'.$to."\n";
    }
}

my $perl5lib = $Config{sitelib};
$perl5lib =~ s/$Config{prefix}/$prefix/;

my $subst = {'#SEARCH#' => $default_path,
	     '#STARTUP#' => $default_startup,
	     '#ENVY.PL#' => $envy,
	     '#INITIAL_ENV#' => \&do_init_env,
	     '#SAFE_SYMLINK#' => $symlink_str,
	     '#ETOP#' => $prefix,
	     '#PERL5LIB#' => $perl5lib,
	    };

sub go {
    my $who = `whoami`."@".`hostname`;
    $who =~ s/\n//g;

    my $f1 = new IO::File;
    my $f2 = new IO::File;
    for my $in (keys %$subst_files) {
	my $out = $subst_files->{$in};
	my $gen = "\n";
	$gen .= "# Generated by $who at ".localtime()."\n";
	$gen .= "# set_defaults.PL $in -> $out\n";
	warn "Substituting $in -> $out\n";
	my $v2str = sub {
	    my $v = shift;
	    if (ref $v) { $v->($in) }
	    else { $v }
	};
	$f1->open($in) or die "open $in: $!";
	$f2->open(">$out") or die "open $out: $!";
	while (defined(my $l=<$f1>)) {
	    while (my($k,$v)=each %$subst) {
		$l =~ s/$k/&$v2str($v)/e;
	    }
	    $f2->print($l);
	}
	$f2->print($gen);
	$f1->close;
	$f2->close;
	chmod(0755, $out)==1 or die "chmod $out: $!";
    }
}
&go;
