#!/usr/local/bin/perl
# init_cache.cgi
# Initialize the cache by running squid with the -z option

require './squid-lib.pl';
$access{'rebuild'} || &error($text{'icache_ecannot'});
&ReadParse();
$whatfailed = $text{'icache_ftic'};

# set user to run squid as..
&lock_file($config{'squid_conf'});
$conf = &get_config();
if (!$in{'nouser'}) {
	$in{'user'} || &error($text{'icache_ymcautrsa'});
	@uinfo = getpwnam($in{'user'});
	@ginfo = getgrgid($uinfo[3]);
	if ($squid_version < 2) {
		$dir = { 'name' => 'cache_effective_user',
			 'values' => [ $in{'user'}, $ginfo[0] ] };
		&save_directive($conf, "cache_effective_user", [ $dir ]);
		}
	else {
		$dir = { 'name' => 'cache_effective_user',
			 'values' => [ $in{'user'} ] };
		&save_directive($conf, "cache_effective_user", [ $dir ]);
		$dir = { 'name' => 'cache_effective_group',
			 'values' => [ $ginfo[0] ] };
		&save_directive($conf, "cache_effective_group", [ $dir ]);
		}
	&flush_file_lines();
	}
&unlock_file($config{'squid_conf'});

# Initialize the cache
$| = 1;
($user, $group) = &get_squid_user($conf);
if ($user) {
	foreach $c (split(/\s+/, $in{'caches'})) {
		mkdir($c, 0755);
		}
	}
&chown_files($user, $group, $conf);
&header($text{'icache_title'}, "");
print "<hr>\n";
$cmd = "$config{'squid_path'} -f $config{'squid_conf'} -z";
print "<p>", &text('icache_itscwtc',$cmd), "<br>\n";
print "<pre>\n";
&additional_log('exec', undef, $cmd);
open(INIT, "$cmd 2>&1 |");
while(<INIT>) {
	print;
	}
close(INIT);
print "</pre>\n";
&webmin_log("init");

print "<hr>\n";
&footer("", $text{'icache_return'});

