#!/usr/bin/perl
# ipdb/cgi-bin/newcity.cgi
# Add new city to database
###
# SVN revision info
# $Date: 2017-08-15 17:53:23 +0000 (Tue, 15 Aug 2017) $
# SVN revision $Rev: 906 $
# Last update by $Author: kdeugau $
###
# Copyright (C) 2004-2010 - Kris Deugau

use strict;
use warnings;
#use CGI::Carp qw(fatalsToBrowser);
use CGI::Simple;
use HTML::Template;
use DBI;
#use POSIX qw(ceil);
use NetAddr::IP;

use Sys::Syslog;

# don't remove!  required for GNU/FHS-ish install from tarball
##uselib##

# push "the directory the script is in" into @INC
use FindBin;
use lib "$FindBin::RealBin/";

use MyIPDB;

openlog "IPDB","pid","$IPDB::syslog_facility";

# Collect the username from HTTP auth.  If undefined, we're in a test environment.
my $authuser;
if (!defined($ENV{'REMOTE_USER'})) {
  $authuser = '__temptest';
} else {
  $authuser = $ENV{'REMOTE_USER'};
}

# Set up the CGI object...
my $q = new CGI::Simple;
# ... and get query-string params as well as POST params if necessary
$q->parse_query_string;

# Convenience;  saves changing all references to %webvar
##fixme:  tweak for handling <select multiple='y' size=3> (list with multiple selection)
my %webvar = $q->Vars;

my ($dbh,$errstr) = connectDB_My;
my $sth;

$ENV{HTML_TEMPLATE_ROOT} = '../templates';

my $page = HTML::Template->new(filename => "newcity.tmpl");
$webvar{pop} = '' if !$webvar{pop};	# shut up some warnings

if ($webvar{city}) {
  if ($webvar{pop} eq 'on') {
    $sth = $dbh->prepare("insert into cities (city,routing) values (?,'y')");
  } else {
    $sth = $dbh->prepare("insert into cities (city,routing) values (?,'n')");
  }
##fixme:  don't allow duplicate cities
  $sth->execute($webvar{city});
  $page->param(city => $webvar{city});
  if ($sth->err) {
    $page->param(err => $sth->errstr);
    my $msg = "$authuser could not add city '$webvar{city}' to database: ".$sth->errstr;
    mailNotify($dbh, 'f:nci', "IPDB city add failure", $msg);
    syslog "err", $msg;
  } else {
    syslog "notice", "$authuser added city/location '$webvar{pop}'".
	(($webvar{pop} eq 'on') ? ' as POP location' : '');
  }
}

print "Content-type: text/html\n\n";

print $page->output;

finish($dbh);
