#!/usr/bin/perl
# Author:	Darren Wiebe <aleph@hagenhomes.com>
# Date:		September 10,2004
#
# This program was written by Darren Wiebe <aleph@hagenhomes.com> with
# the help of code taken from astcc-admin.cgi written by: 
# Mark Spencer <markster@digium.com
#
# This program is Free Software and is distributed under the
# terms of the GNU General Public License version 2 or later
# at your option.
#
# This program is designed to import the csv price list from
# Nufone (nufone.net) into the astcc routes db.
#
# We expect the data file to be in the following format:
# "Comment","Country Code","Area Code","Cost","Connection Fee","Increments","Trunks"
# Please call this program with your csv file as the sole argument.
# ie ./astcc_import_routes.pl ../routes.csv

use DBI;

$tail =".*";
$dbase = @ARGV[0];

sub read_file {
	open(READFILE,"$dbase") ||
	    die "Error - could not open $dbase for reading.\n";
	@data =<READFILE>;
	close(READFILE);
	foreach $temp (reverse @data) {
			($comment,$cc,$ac,$cost,$connectcost,$includedseconds,$trunks) = split(/\,/,$temp);	
			if ($cc > "1") {
				$head = "011";
			} else {
				$head = "";
			}
			$cost = $cost * 10000;
			$connectcost = $connectcost * 10000;
			$pattern = "$head$cc$ac$tail";
			$comment =~ s/\"//g;  #Strip quotation marks
			$trunks =~ s/\"//g;  #Strip quotation marks
			$cost =~ s/\s+$//;
			print "$pattern $comment $trunks $connectcost $includedseconds $cost";
			&droproute;
			&addroute;
	}
}

sub load_config() {
	open(CFG, "</var/lib/astcc/astcc-config.conf");
	while(<CFG>) {
		chomp;
		my ($var, $val) = split(/\s*\=\s*/);
		$config{$var} = $val;
	}
	close(CFG);
}

sub connect_db() {
	my $dsn = "DBI:mysql:database=$config{'dbname'};host=$config{'dbhost'}";
	$dbh->disconnect if $dbh;
	$dbh = DBI->connect($dsn, $config{'dbuser'}, $config{'dbpass'});
}

sub droproute() {
	if ($dbh->do("DELETE FROM routes WHERE pattern = " . $dbh->quote($pattern))) {
		$status = "Dropped route '" . $pattern . "'.";
	} else {
		$status = "Unable to drop route '" . $pattern . "'.";
	}
}

sub addroute() {
	$tmp = "INSERT INTO routes (pattern,comment,trunks,connectcost, includedseconds, cost) VALUES (" .
					$dbh->quote($pattern) . ", " .$dbh->quote($comment) . ", " .
					$dbh->quote($trunks) . ", " .$dbh->quote($connectcost) . ", " .
					$dbh->quote($includedseconds) . ", " . $dbh->quote($cost) . ")";
	$dbh->do($tmp) || print "$tmp failed";
}

&load_config;
&connect_db;
&read_file;