#!/usr/bin/perl -I/usr/local/sauron
#
# export-hosts  generates list of IPs in use for given neworks
#
# Copyright (c) Michal Kostenec <kostenec@civ.zcu.cz> 2013-2014.
# Copyright (c) Timo Kokkonen <tjko@iki.fi>  2004.
# $Id: export-hosts,v 1.1 2004/08/02 05:50:13 tjko Exp $
#
require 5;
use Getopt::Long;
use Time::Local;
use Net::Netmask;
use Sauron::DB;
use Sauron::Util;
use Sauron::BackEnd;
use Sauron::Sauron;

sub qstr($) {
    my($str)=@_;
    $str =~ s/\"/\'/g;  # hack...
    return "\"$str\"";
}

sub match_zone($) {
    my($id)=@_;
    
    return 1 unless (@zones > 0);
    for $i (0..$#zones) { return 1 if ($id == $zones[$i]); }
    return 0;
}

load_config();

$user = (getpwuid($<))[0];
$host = `hostname`;
$host =~ s/\n//g;
$time_now = localtime;
$tnow = time();
$tmp_extension = ".tmp.$<.$$"; # generate extension for temp files

GetOptions("help|h","verbose|v","group=s","colnames");

if ($opt_help || @ARGV < 1) {
  print "syntax: $0 [--help] [OPTIONS] <servername> [[zonename] ...]\n",
        "\noptions:\n",
	"\t--group=<regexp>\tlist only hosts beloning to matching group\n",
        "\t--colnames\t\toutput column names on first line\n",
	"\t--verbose\t\tmore verbose output\n\n";
  exit($opt_help ? 0 : 1);
}

$opt_verbose = ($opt_verbose ? 1 : 0);
$servername=shift;

db_connect();

$serverid=get_server_id($servername);
fatal("cannot find server '$servername'") unless ($serverid > 0);

while (($zone=shift)) {  
    $zoneid=get_zone_id($zone,$serverid);
    fatal("cannot find zone: $zone") unless ($zoneid > 0);
    push @zones, $zoneid; 
}


# fetch host records for this server...

$sql = "SELECT h.id,h.zone,z.name,h.type,h.domain,a.ip,h.ttl,h.class,g.name," .
       " h.alias, al.domain, al.zone, zal.name, h.cname_txt," . # 9-13
       " h.hinfo_hw, h.hinfo_sw, wx.name, mx.name," . # 14-17
       " h.router, h.ether, h.ether_alias, eal.ether," . # 18-21
       " h.info, h.location," . # 22-23
       " h.dept, h.huser, h.email, h.model, h.serial, h.misc," . # 24-29
       " h.asset_id, h.comment, h.duid, h.iaid " . # 30-33
       "FROM zones z JOIN hosts h ON h.zone=z.id " .
       " LEFT JOIN a_entries a ON h.id=a.host " .
       " LEFT JOIN hosts al ON h.alias=al.id " .
       " LEFT JOIN hosts eal ON h.ether_alias=eal.id " .
       " LEFT JOIN zones zal ON al.zone=zal.id " .
       " LEFT JOIN groups g ON h.grp=g.id " . 
       " LEFT JOIN wks_templates wx ON h.wks=wx.id " .
       " LEFT JOIN mx_templates mx ON h.mx=mx.id " .
       "WHERE z.server=$serverid " .
       "ORDER BY h.domain,a.ip ";

print STDERR "Fetching host entries for server: $servername ...\n" 
    if ($opt_verbose);
db_query($sql,\@q);
print STDERR $#q . " host entries found for this server.\n" if ($opt_verbose);

$lastid=-1;

if ($opt_colnames) {
    print "domain,type,ip,alias,ether,duid,iaid,ttl,groupname,hinfo_hw,hinfo_sw," .
	  "mx_template,router,id,info,location,department,user,email," .
	  "serial,misc,asset_id,comment" .
	  "\n";
}

for $i (0..$#q) {
    @r=@{$q[$i]};
    next if ($lastid == $r[0]);
    next unless (match_zone($r[1]));
    next if ($opt_group && $r[8] !~ /$opt_group/);

    $domain=$r[4];
    next if ($domain eq '@');

    $domain.=".".$r[2] unless ($domain =~ /\.$/);
    $type=$r[3];
    $ip=$r[5];
    if ($type == 4 || $type == 7) {
	if ($r[9] > 0) {
	    $alias=$r[10];
	    $alias.= ".".$r[12] unless ($alias =~ /\.$/);
	} else {
	    $alias=$r[13];
	}
    } else {
	$alias='';
    }
    $ether=$r[19];
    if ($r[20] > 0) {
	$ether="(".$r[21].")";
    }

    $duid = $r[32];
    $iaid = sprintf("%x", $r[33]);

    print join(",", 
	       $domain,$type,$ip,$alias,$ether,$duid,$iaid,$etheralias,
	       $r[6], # ttl
	       qstr($r[8]), # group
	       qstr($r[14]),qstr($r[15]), # hinfo hw & sw
	       qstr($r[16]),qstr($r[17]), # mx templates
	       $r[18], # router
	       $r[0], # id
	       qstr($r[22]),qstr($r[23]), # info, location
	       qstr($r[24]),qstr($r[25]), # department, (h)user
	       qstr($r[26]),qstr($r[27]), # email, model
	       qstr($r[28]),qstr($r[29]), # serial, misc
	       qstr($r[30]),qstr($r[31]), # asset_id, comment
	       
	       ) . "\n";
	       

    $lastid=$r[0];
    $counter++;
}

print STDERR "$counter host entries exported.\n" if ($opt_verbose);

exit 0;

# eof

