#!/usr/local/bin/perl
# install.cgi
# Install a downloaded perl module

require './cpan-lib.pl';
&ReadParse();
-r $in{'pfile'} || &error(&text('install_efile', "<tt>$in{'pfile'}</tt>"));
$| = 1;
$theme_no_table = 1;
&header($text{'install_title'}, "");
print "<hr>\n";

# Set environment variables
for($i=0; defined($in{"name_$i"}); $i++) {
	if ($in{"name_$i"} ne "") {
		$ENV{$in{"name_$i"}} = $in{"value_$i"};
		}
	}

# Untar the perl module
$mod_dir = &tempname($in{'dir'});
system("rm -rf $mod_dir >/dev/null 2>&1");
&show_output($text{'install_untar'}, "/tmp/.webmin",
	     "gunzip -c $in{'pfile'} | tar xvf -");

# Run Makefile.PL and make
&show_output($text{'install_make'}, $mod_dir,
	     "$perl_path Makefile.PL $in{'args'} && make") || &build_error();

# Run make test (if requested)
if ($in{'act'} == 1 || $in{'act'} == 3) {
	&show_output($text{'install_test'}, $mod_dir, "make test") ||
		&build_error();
	}

# Run make install (if requested)
if ($in{'act'} == 2 || $in{'act'} == 3) {
	&show_output($text{'install_install'}, $mod_dir, "make install") ||
		&build_error();
	}

# Clean up files
print "<p>",&text('install_done_'.$in{'act'}, "<tt>$in{'mod'}</tt>"),"<p>\n";
&clean_up();

sub clean_up
{
system("rm -rf $mod_dir");
unlink($in{'pfile'}) if ($in{'need_unlink'});
print "<hr>\n";
&footer("", $text{'index_return'});
}

# show_output(desc, dir, command)
sub show_output
{
local (%seen, $endless_loop);
print "<table border>\n";
print "<tr $tb> <td><b>$_[0]</b></td> </tr>\n";
print "<tr $cb> <td><pre>",&text('install_exec', $_[2]),"\n";
print " " x 100,"\n";
open(CMD, "(cd $_[1] ; $_[2]) 2>&1 </dev/null |");
while(<CMD>) {
	if ($seen{$_}++ > 100) {
		$endless_loop = 1;
		print "\n$text{'install_loop'}\n";
		last;
		}
	while(length($_) > 100) {
		s/^(.{100})//;
		print &html_escape($1),"\n";
		}
	print;
	}
close(CMD);
print "</pre></td></tr> </table><p>\n";
return $? || $endless_loop ? 0 : 1;
}

sub build_error
{
print "<p>",&text('install_err', "<tt>$in{'mod'}</tt>"),"<br>\n";
if ($in{'source'} == 3) {
	print &text('install_err2', "<tt>perl -MCPAN -e shell</tt>"),"\n";
	}
print "<p>\n";
&clean_up();
exit;
}

