# Lib Common 
# Just in case NO  WEBMIN (web-lib.pl, etc.) are loaded ...
# Some variables are needed and set here, will be reassigned later
# Globals ...
# Some functions are hooks 
# others are empty to avoid full Webmin code for line command execution

# Vital libraries
use Socket;
#use SelfLoader;

$config_directory="/etc/webmin/tarantella"; 
$debug=2; # if 0 it will try to get config file value
$tta_logfile="/tmp/.webmin/stta_log";
$default_lang = "en";
$current_lang = "es";
$module_name = "tarantella";

# Read Config File 
sub initialize () {
   &read_file("$config_directory/config", \%config);
   $DebugFile=$config{cache_debuglog};
   if ( $debug eq 0 ) { $debug=$config{stta_debugname}; }; 
   if ( $debug gt 0 ) { 
         $DebugFile=$config{stta_debugname}.$tool_name.".log";
         open(DebugLog, ">>$DebugFile"); 
   }
}

# Read Module Text 
# load_language([module])
# Returns a hashtable mapping text codes to strings in the appropriate language
sub load_language
{
local %text;
if ($module_name) {
        local $mod = $_[0] ? "../$_[0]" : ".";
        &read_file("../lang/$default_lang", \%text);
        &read_file("../lang/$current_lang", \%text);
        &read_file("$mod/lang/$default_lang", \%text);
        &read_file("$mod/lang/$current_lang", \%text);
        }
else {
        &read_file("lang/$default_lang", \%text);
        &read_file("lang/$current_lang", \%text);
        if ($_[0]) {
                &read_file("$_[0]/lang/$default_lang", \%text);
                &read_file("$_[0]/lang/$current_lang", \%text);
                }
        }
foreach $k (keys %text) {
        $text{$k} =~ s/\$([A-Za-z0-9\.\-\_]+)/text_subs($1,\%text)/ge;
        }
return %text;
}

sub text_subs
{
local $t = $_[1]->{$_[0]};
return defined($t) ? $t : '$'.$_[0];
}
 
# text(message, [substitute]+)
sub text
{
local $rv = $text{$_[0]};
local $i;
for($i=1; $i<@_; $i++) {
        $rv =~ s/\$$i/$_[$i]/g;
        }
return $rv;
}

# read_file(file, &assoc, [&order], [lowercase])
# Fill an associative array with name=value pairs from a file
sub read_file
{
    open(ARFILE, $_[0]) || return 0;
    while(<ARFILE>) {
	    s/\r|\n//g;
            if (!/^#/ && /^([^=]+)=(.*)$/) {
		    $_[1]->{$_[3] ? lc($1) : $1} = $2;
		    push(@{$_[2]}, $1) if ($_[2]);
        	    }
            }
    close(ARFILE);
    return 1;
}

sub lock_file
{
    return 1;
}
sub unlock_file
{
    return 1;
}

# webmin_log(action, type, object, &params, [module])
# Log some action taken by a user
sub webmin_log
{
return if (!$config{'stta_logname'});
local $m = $_[4] ? $_[4] : $module_name;
local $m_logfile=$config{'stta_logname'}.$tool_name.".log";

$m="$tool_name ($m)";

local $user_id = `id`;
local @dataUserId = split(/ /, $user_id);
local $local_user=$dataUserId[0];
local $host_name=`hostname`;


# log the action
local $now = time();
local @tm = localtime($now);
local $script_name = $0 =~ /([^\/]+)$/ ? $1 : '-';
local $id = sprintf "%d.%d.%s",
		$now, $$, $tool_name;
local $line = sprintf "%s::[%2.2d/%s/%4.4d %2.2d:%2.2d:%2.2d]::%s::%s::%s::%s::%s::\"%s\"::\"%s\"::\"%s\"",
	$id, $tm[3], $text{"smonth_".($tm[4]+1)}, $tm[5]+1900,
	$tm[2], $tm[1], $tm[0],
	$local_user, "$$::$tool_name::",
	$host_name,
	$m, $script_name,
	$_[0], $_[1] ne '' ? $_[1] : '-', $_[2] ne '' ? $_[2] : '-';
foreach $k (sort { $a cmp $b } keys %{$_[3]}) {
	local $v = $_[3]->{$k};
	if ($v eq '') {
		$line .= "::$k=''";
		}
	elsif (ref($v) eq 'ARRAY') {
		foreach $vv (@$v) {
			next if (ref($vv));
			$vv =~ s/(['"\\\r\n\t\%])/sprintf("%%%2.2X",ord($1))/ge;
			$line .= "::$k='$vv'";
			}
		}
	elsif (!ref($v)) {
		foreach $vv (split(/\0/, $v)) {
			$vv =~ s/(['"\\\r\n\t\%])/sprintf("%%%2.2X",ord($1))/ge;
			$line .= "::$k='$vv'";
			}
		}
	}
   open(STTALOG, ">>$m_logfile");
   print STTALOG $line,"::\n";
   close(STTALOG);

}

# additional_log(type, object, data)
# Records additional log data for an upcoming call to webmin_log, such
# as command that was run or SQL that was executed.
sub additional_log
{
   return if (!$config{'stta_logname'});
   webmin_log($_[0],$_[1],$_[2],$_[3],$_[4]);
}

sub endclose_debug
{
   print DebugLog "----------------------------------------------\n";
   close (DebugLog);
}

# error([message]+)
# Display an error message and exit. The variable $whatfailed must be set
# to the name of the operation that failed.
sub error
{
   if ( $debug gt 0 ) {
        print DebugLog "$text{'error'}: ";
        print DebugLog ($whatfailed ? "$whatfailed : " : ""),@_,"\n";
   }
   if ( $debug gt 0 ) { &endclose_debug(); }   
   exit;
}
 
# error_setup(message)
# Register a message to be prepended to all error strings
sub error_setup
{
$whatfailed = $_[0];
}

# check_socket(host, port, handle, [&error])
sub check_socket
{
local($addr, $h); $h = $_[2];
if (!socket($h, PF_INET, SOCK_STREAM, getprotobyname("tcp"))) {
	if ($_[3]) { ${$_[3]} = &text(sckerr_no, $!); return false; }
	else { &error("&text(sckerr_no, $!)"); }
	}
if (!($addr = inet_aton($_[0]))) {
	if ($_[3]) { ${$_[3]} = &text(sckerr_noip, $_[0]); return false; }
	else { &error("&text(sckerr_noip, $_[0])"); }
	}
if (!connect($h, sockaddr_in($_[1], $addr))) {
	if ($_[3]) { ${$_[3]} = &text(sckerr_noconn, $_[0],$_[1],$!); return false; }
	else { &error("&text(sckerr_noconn, $_[0],$_[1],$!)"); }
	}
        # select($h); $| =1; select(STDOUT);
        shutdown($h,2);
}

1;  # Return true    
