# fin 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, 'fin.*\.lzh'))
		|| die "fin package not found\n";
	($tblpack = &NewestFile($SRCDIR, 'tbl.*\.lzh'))
		|| die "tbl package not found\n";
	($manpack = &NewestFile($SRCDIR, 'man.*\.lzh'))
		|| die "man 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("fin ss.fma findoc.fin > $MANDIR\\fin.doc");
	&invoke("move fin.exe ss.fma $BINDIR");
	&cleandir;

	&invoke("$LHA E $tblpack");
	&invoke("move tbl.exe tbl.fma $BINDIR");
	&invoke("move tblj.doc $MANDIR\\tbl.doc");

	&invoke("$LHA E $manpack");
	&invoke("move man.com $BINDIR");
	&invoke("move man.man $MANDIR");

	&chdir($SRCDIR);
	&invoke("deltree $TMPDIR");

	&setup_env;
	print "インストールが終わりました.\n";
	&okay;
exit 0;

sub setup_env {
	if (defined $ENV{'FMAC'}) {
		print "必要な環境変数はすべて設定されています\n";
		return;
	}
	$AUTOEXEC = "C:\\AUTOEXEC.BAT";
	print "$AUTOEXEC に環境変数設定を追加します\n";
	&okay;
	open(AUTOEXEC, ">>$AUTOEXEC")
		|| die "cannot open $AUTOEXEC for append\n";
	print AUTOEXEC "REM begin fin (toyoda installer)\n";
	print AUTOEXEC "SET FMAC=$BINDIR\n";
	print AUTOEXEC "REM end fin (toyoda installer)\n";
	close(AUTOEXEC);
	print "$AUTOEXEC の書き換えは再起動後に有効になります\n";
}

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";
	}
}
