#!/usr/bin/perl
#
# update_clients.pl
#
# Copyright 1999 -- 2001, onShore Development Inc. <URL:http://www.onshore-devel.com/>
#
#
# This program is free software under the terms of the GNU General Public
# License (GPL). A copy of the GPL, "COPYING", should have been made
# available with this software.  If not, a copy may be obtained at 
# http://www.fsf.org/copyleft/gpl.html
#
# 
# $Id: timesheet-import-clients,v 1.6 2001/08/29 22:23:15 adam Exp $
#
##use strict qw(refs vars);
require 'etc/timesheet.conf';
require 'lib/common-funcs.pl';
use ADB;
use Getopt::Long; 
# My ADB database connection
my $dbconn;
# variable to hold SQL query replies from ADB
my $reply;
# string we put error messages into
my $oops;
# What is my filename to get data from?
my $sql;

&GetOptions ( 
	      "mode=s" => \$mode
	      ); 

my $datafile = shift; 

&usage() if ( ! $datafile ); 

sub usage {
    print  "Usage:\n"; 
    print  "timsheet-import-clients -mode {import|update} datafile\n"; 
    print  "\nWhere datafile is a tab seperated text file with data\n"; 
    print  "in the following orde: Client ID, Name, then bill rate\n"; 
    print  "\n\"-mode update\" will only change existing clients to the bill\n"; 
    print  "rate specified in the datafile.\n"; 
    print  "\n\"-mode import\" will add all entiries listed in the datafile.\n\n"; 
    exit (1) 
}

# Connect to backend database
    $dbconn = new ADB($Conf::DBADDR, $Conf::SQLDB);
if(!$dbconn->is_ok){
    $oops = $dbconn->errorstring;
    &error("Cannot Connect to backend: $oops\n");
}



open(IMPORT, "$datafile") ||
 print "Cannot open datafile: $!";

if ( $mode eq "update" ) { 
    print "updating default rates from $datafile\n";
    while($line = <IMPORT>) {
	$line =~ s/\\'/\\\\'/g;
	$line =~ s/'/\\'/g; 
	if($line =~ /^(.*)\t(.*)\t(.*)$/) {
	    print "Update $2 ($1) to $3\n";
	    $sql = "UPDATE client set default_bill_rate=$3 where client_id=$1";
	    $reply = $dbconn->query($sql);
	    if(!$reply){
		$oops = $dbconn->errorstring;
		print("Error setting default rate: $oops: SQL: $sql");
	    }
	}
    }
} 
elsif ( $mode eq "import" ) { 
    print "importing clients from $datafile"; 
    while($line = <IMPORT>) {
	$line =~ s/\\'/\\\\'/g;
	$line =~ s/'/\\'/g; 
	if($line =~ /^(.*)\t(.*)\t(.*)$/) {
	    print  "INSERT into client values ('$1', '$2', '$3', '')";
	    $sql = "INSERT into client values ('$1', '$2', '$3', '')";
	    $reply = $dbconn->query($sql);
	    if(!$reply){
		$oops = $dbconn->errorstring;
		print("Error setting default rate: $oops: SQL: $sql");
	    }
	}
    }
} 
else { 
    print  "Unknown mode: \"$mode\".\n"; 
    &usage; 
}
close(IMPORT);





