# inflow.pm - common subroutines for inflow scripts
# 
# keep this file at the same place as the rest of the inflow scripts !
#
# History: The inflow-package is based on the ideas of counter.pl, a perl
#          script written by Juan Garcia, Rediris, 1995-96.
#          inflow.pm contains general purpose subroutines used in 
#          several scripts of this package.
#
# 19980618 V2.2.0 initial version
# 20000101 V2.4.0 y2k issues fixed
$PMRELEASE = "V2.4.0";


# MakeDateStr
# ----------------------------------------------------------------------
# make a date string yyyymmdd corresponding to the actual time.
# optional arg is number of days to subtract from current time
#
sub MakeDateStr {
    local($minusdays) = @_;
    local($tstr);
    local(@tarr) = localtime(time-$minusdays*86400);
    $tstr = sprintf ("%04d%02d%02d", $tarr[5]+1900, $tarr[4]+1, $tarr[3]);
}
 

# MakeTimeStr
# ----------------------------------------------------------------------
# make a time string yyyymmdd.hh:mm from current time (no args given) or 
# from UNIX time (long int) passed as argument
#
sub MakeTimeStr {
    local($arg) = @_;
    local($tstr);
    if ($arg == 0) { $arg = time; }
    local(@tarr) = localtime($arg);
    $tstr = sprintf ("%04d%02d%02d.%02d:%02d", 
		     $tarr[5]+1900, $tarr[4]+1, $tarr[3],$tarr[2], $tarr[1]);
}


# MakeTimeOnlyStr
# ----------------------------------------------------------------------
# convert seconds to time string d+hh:mm:ss 
#
sub MakeTimeOnlyStr {
    local($arg) = @_;
    local($tstr);
    return '' if ($arg == 0);
    local(@tarr) = gmtime($arg);
    $tstr = sprintf ("%d+%02d:%02d:%02d", 
		     $tarr[3]-1,$tarr[2], $tarr[1], $tarr[0]);
}

# MakeShortTimeStr
# ----------------------------------------------------------------------
# make a time string yyyymm from current time (no args given) or 
# from UNIX time (long int) passed as argument
#
sub MakeShortTimeStr {
    local($arg) = @_;
    local($tstr);
    if ($arg == 0) { $arg = time; }
    local(@tarr) = localtime($arg);
    $tstr = sprintf ("%04d%02d",$tarr[5]+1900, $tarr[4]+1);
}


# gethostandfqdn
#---------------------------------------------------------------------- 
# construct fully qualified domain name...
sub gethostandfqdn {
    chop($str=`uname -n`);
    if ($str =~ /\./) {             # str is fqdn
	$fqdn = $str;
	($hostname) = ($str =~ /^([^.]+)\./);
    } else {                        # str is simple hostname
	$hostname = $str;
	$str = `$GREP domain /etc/resolv.conf`;
	$str =~ /domain\s*(\S+)$/;
	$fqdn = $hostname . "." . $1;
    }
}

# get_urllookup
#----------------------------------------------------------------------
# read URL info from global+local config files
#
# file format:
# <name> <srvrname> <operator_code> <monitoring-URL>
#
sub get_urllookup {
    $use_links = 0;
    # global tables
    if ($URLLOOKUP eq "") {
	warn "no global lookup table specified\n" if $opt_d;
    } elsif (open(LOOKUP,"$URLLOOKUP") == 0) {
	warn "unable to open global lookup table $URLLOOKUP\n";
    } else { 
	$use_links = 1; 
	warn "reading global lookup table $URLLOOKUP...\n" if $opt_d;
    }
    if ($use_links == 1) {
	while (<LOOKUP>) {
	    chop;
	    if (/^\# DATE +(\d{6,8})/) { $GURLRELEASE = $1; }
	    next if (/^\#|^$/);
	    ($name,$srvr,$code,$url) = split;
	    $srvrname{$name} = $srvr;
	    $operatedby{$srvr} = $code;
	    $moni_url{$srvr} = $url;
	}
	close LOOKUP;
v    }
    # local tables
    if ($URLLUPLOC eq "") {
	warn "no local lookup table specified\n" if $opt_d;
    }
    elsif (open(LOOKUP,"$URLLUPLOC") == 0) {
        warn "unable to open local lookup table $URLLUPLOC\n";
    }
    else { $use_links = 1; }
    if ($use_links == 1) {
	warn "reading local lookup table $URLLUPLOC...\n" if $opt_d;
	while (<LOOKUP>) {
	    chop;
	    if (/^\# DATE +(\d{6,8})/) { $LURLRELEASE = $1; }
	    next if (/^\#|^$/);
	    ($name,$srvr,$code,$url) = split;
	    $srvrname{$name} = $srvr;
	    $operatedby{$srvr} = $code;
	    $moni_url{$srvr} = $url;
	}
	close LOOKUP;
    }
}

# get_hostfilter
#----------------------------------------------------------------------
# read list of hosts to show or hide
#
# format:   > SHOW|HIDE                   # what to do
#           > news01.some.site.net        # exact domainname
#           > *other.site.com             # using wildcard
#
sub get_hostfilter {
    if ($HOSTFILTER eq "") {
	warn "no host list defined\n";
	$havehostlist = "";
	return;
    }
    unless (open(HOSTLIST,"$HOSTFILTER")) {
        warn "unable to open host list $HOSTFILTER\n";
        $havehostlist = "";
        return;
    }
    warn "reading HOSTLIST $HOSTFILTER...\n" if $opt_d;
    while (<HOSTLIST>) {
	chop;
	next if (/^\#|^$/);
	if (/^\s*(SHOW|HIDE)/) {
	    $havehostlist = $1;
	    last;
	}
    }
    warn "  what to do with listed hosts: $havehostlist\n" if $opt_d;
    while (<HOSTLIST>) {
	chop;
	next if (/^\#|^$/);
	s/^\s*(\S+)\s*$/\1/;          # remove leading/trailing blanks
	if (/[*?]/) { 
	    s/^[*?]*(.+)[*?]*$/\1/;   # remove leading/trailing wildcards
	    s/\./\\./g;               # escape dots
	    s/([*?])/.\1/g;           # transform remaining wildcards
	    $fuzzymatchstr .= "$_|"; 
	}
	else { $filterhost{$_} = 1; }
    }
    chop($fuzzymatchstr);
    close HOSTLIST;
    if ($opt_d) {
	warn "  fuzzymatchstr: $fuzzymatchstr\n";
	warn "  listed hosts to $havehostlist:\n";
	foreach (keys(%filterhost)) {  warn "  - $_\n"; }
    }
}


# update_PATH
# -----------------------------------------------------------------------------
# enhance PATH to support scripts run from cron
#
sub update_PATH {
    warn "OLD PATH=$ENV{'PATH'}\n" if $opt_d;
    @ENVPATH = split(/:/,$ENV{'PATH'});
    push(@ENVPATH,@ADDTOPATH);
    
    $ENV{'PATH'}='';
    foreach $p (@ENVPATH) {
	next if $envpathseen{$p}; # skip duplicates
	$envpathseen{$p} = 1;
	$ENV{'PATH'} .= $p . ":";
    }
    chop($ENV{'PATH'});           # cut last ":"
    warn "NEW PATH=$ENV{'PATH'}\n" if $opt_d;
}



# interpret
# -----------------------------------------------------------------------------
# interpret variable read from file; variables have to be separated by
# white space
#
sub interpret {
    local($line) = ""; 
    @words = split;
    foreach $w (@words) {
	if ($w =~ /^\$/) { eval "\$w=$w"; }
	$line .= "$w ";
    }
    return "$line\n";
}


# modify_config
# -----------------------------------------------------------------------------
#
sub modify_config {
    local($p,$n,$incpath);
    $inflowconf = $opt_f ? $opt_f : $INFLOWCONF;
    if ($inflowconf =~ /^(.*)\/([^\/]+)$/) {
	$p = $1; 
	$n = $2;
	push(@INC,$p);
    } else { 
	$n = $inflowconf; 
    }
    foreach (@INC) { $incpath .= "    $_\n"; }
    if (-e $inflowconf) {
	warn "loading local configs from $inflowconf...\n" if $opt_d;
	require $n;
	$inflowconfinfo = "$inflowconf $CFRELEASE\n";
	$inflowconfinfo .= " " x 16 . "from: $CFRELDATE";
    } else {
	if ($opt_f) {
	    die "abort - couldn't find or open $n on INC=\n$incpath\n";
	} 
	warn "didn't find any local configs $n on INC=\n$incpath\n" if $opt_d;
	$inflowconfinfo = "- none -";
    }
}


# takesite
#----------------------------------------------------------------------
# returns 1 to accept site, 0 to skip it
sub takesite {
    local($s) = @_;
    local($match,$retval);
    if ($filterhost{$s}) {
	$match = 1;
	warn "$s is on the host list\n" if $opt_d;
    } elsif ($fuzzymatchstr && $s =~ /$fuzzymatchstr/) {
	$match = 1;
	warn "$s matches fuzzymatchstr\n" if $opt_d;
    } else { 
	$match = 0;
	warn "no match for $s...\n" if $opt_d; 
    }
    $retval = 0;
    if (($havehostlist eq 'SHOW') && ($match > 0)) { $retval = 1; }
    if (($havehostlist eq 'HIDE') && ($match == 0)) { $retval = 1; }
    return $retval;
}


# closepage 
# -------------------------------------------------------------
# close page, write footers...   
#
sub closepage {
    if ($opt_w) {
        print OUT "</table><P>\n";
        print OUT "<FONT SIZE=\"-1\">Created by $0 $RELEASE. \n";
        print OUT "<A HREF=\"$INFLOWURL\">inflow</A> is a project of the 
<A HREF=\"http://www.switch.ch/netnews/wg/netnews-wg.html\">
RIPE netnews-wg</A>.</FONT><P><P>
$htmlfooter\n";
    } else {
        print OUT "\n\n";
    }
}

# get_env
# -------------------------------------------------------------
# get detailed environment info
#
sub get_env {
    $envstr = "$RELEASE/";
    $envstr .= "pm=$PMRELEASE/" if $PMRELEASE;
    $envstr .= "cf=$CFRELEASE/" if $CFRELEASE;
    $envstr .= "gurl=$GURLRELEASE/" if $GURLRELEASE;
    $envstr .= "lurl=$LURLRELEASE/" if $LURLRELEASE;
    $envstr .= "r+/" if ($havehostlist eq 'SHOW');
    $envstr .= "r-/" if ($havehostlist eq 'HIDE');    
    $envstr .= "perl=$]";
}
