#!/usr/bin/perl
# Spit out the allocated IPs in an IP pool as a CSV.
##
# $Id$
# Copyright (C) 2016 - Kris Deugau <kdeugau@deepnet.cx>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
##


use strict;
use warnings;

use CGI::Simple;


# Taint-safe (ish) voodoo to push "the directory the script is in" into @INC.
use File::Spec ();
use File::Basename ();
my $path;
BEGIN {
    $path = File::Basename::dirname(File::Spec->rel2abs($0));
    if ($path =~ /(.*)/) {
        $path = $1;
    }
}
use lib $path;

use MyIPDB;

# grab CGI parameters, and stash them in a convenient hash
my $q = new CGI::Simple;
$q->parse_query_string;
my %webvar = $q->Vars;

# Live production experience says that text/csv doesn't work as intended
#print "Content-type: text/csv\n\n";
print "Content-type: text/plain\n\n";

my $ip_dbh;
($ip_dbh,$errstr) = connectDB_My;

print qq("IP","CustID","Description"\n);

my $sth = $ip_dbh->prepare("SELECT ip,custid,description FROM poolips".
        " WHERE parent_id = ? AND available = 'n' ORDER BY ip");
$sth->execute($webvar{pool});
while (my ($ip,$cust,$desc) = $sth->fetchrow_array) {
  print qq("$ip","$cust","$desc"\n);
}
