# lpd installer on Windows
#
# Copyright (C) TOYODA Eizi, 1998, 1999.  All rights reserved.

	$TMPDIR = $ENV{"TMP"} || $ENV{"TEMP"}
		|| die "%TEMP% not set\n";
	$TMPDIR =~ s/\\$//;
	$TMPDIR .= "\\toyoda.tmp";

	$SRCDIR = `COMMAND /C CHDIR`;
	chop $SRCDIR;
	@extpath = ($SRCDIR, "$SRCDIR\\..", "$SRCDIR\\..\\..");
	$LHA = &which("lha.exe", @extpath)
		|| die "lha not installed\n";
	($package = &NewestFile($SRCDIR, 'lpd.*\.lzh'))
		|| die "lpd package not found\n";
	
	&setBINDIR;
	&setMANDIR;
	print "install $package into $BINDIR (manual $MANDIR).\n";
	&okay;

	&mkdir($BINDIR);
	&mkdir($MANDIR);
	&mkdir($TMPDIR);
	&chdir($TMPDIR);

	&invoke("$LHA E $package");
	&invoke("setup.exe");
	&invoke("start lprmon.htm");

	&chdir($SRCDIR);
	&invoke("deltree $TMPDIR");
exit 0;

sub cleandir {
	&invoke("erase *.*");
}

sub invoke {
	local($cmd) = @_;
	print "> ", $cmd, "\n";
	&okay;
	system $cmd;
}

sub mkdir {
	local($dir) = @_;
	return if -d $dir;
	mkdir $dir, 0777;
}

sub rmdir {
	local($dir) = @_;
	rmdir $dir;
}

sub chdir {
	local($dir) = @_;
	print "cd $dir\n";
	chdir($dir) || die "chdir $dir failed\n";
}

sub which {
	local($command, @extpath) = @_;
	local(@path) = split(/;/, $ENV{'PATH'});
	local($dir, $fullpath);
	foreach $dir (@path, @extpath) {
		$fullpath = "$dir\\$command";
		return $fullpath if -x $fullpath;
	}
	undef;
}

sub NewestFile {
	local($dir, $pattern) = @_;
	opendir DIR, $dir;
	local(@list) = grep(/$pattern/i, readdir(DIR));
	closedir DIR;
	return undef unless @list;
	sort @list;
	$dir . '\\' . $list[$#list];
}

sub okay {
	print "pause -- hit Ctrl-C or Break to STOP\n";
	scalar <STDIN>;
}

sub setMANDIR {
	if (defined $ENV{'HOME'}) {
		$MANDIR = $ENV{'HOME'} ."\\MAN";
	} else {
		$MANDIR = "C:\\HOME\\MAN";
	}
}

sub setBINDIR {
	if (defined $ENV{'HOME'}) {
		$BINDIR = $ENV{'HOME'} ."\\BIN";
	} else {
		$BINDIR = "C:\\HOME\\BIN";
	}
}
