#!/usr/bin/perl -w
#
# based on rtadduser: add a local user to RT
# original work by David Maze <dmaze@cag.lcs.mit.edu>
# modify by Hugues Lepesant <hlepesant@veepee.com>
# $Id: SyncUser2RT,v 1.12 2005/04/04 13:28:17 hugues Exp $
#

use Sys::Syslog qw(:DEFAULT setlogsock);
use Sys::Syslog;
use DBI;
use lib "/opt/WebSites/rt34/lib";
use strict;
use English;
use RT::Interface::CLI qw(CleanEnv);
use RT::User;

CleanEnv();
RT::LoadConfig();
RT::Init();

my $db_host = 'localhost';
my $db_user = 'dbname';
my $db_pass = 'dbuser';
my $db_name = 'dbpass';
my $dbh;
my $sth;
my $query;
my $fields;
my @array;
my $size;
my $i;
my $debug = 0;
my $full_debug = 0;
my $login = "";
my $IdUser = "";
my $EntrepriseID = "";
my %code;
my $update = "";
my $syslog_msg_true;
my $syslog_msg_false;


$dbh = DBI->connect("DBI:mysql:database=".$db_name.";host=".$db_host,$db_user, $db_pass) || die "Can't connect to database: $DBI::errstr\n";
if ( !defined $dbh ) { die "Cannot connect to database!\n"; } 

$query = "put here the SQL query needed to get user's information";

if ( $debug ) {
	print( "SQL = ".$query."\n" );
	exit 1;
}

$sth = $dbh->prepare($query);

if ( !defined $sth ) { die "Cannot prepare statement: $DBI::errstr\n"; }

$sth->execute or die "Unable to execute query: $dbh->errstr\n";

while($fields = $sth->fetchrow_arrayref){
	push @array, [ @$fields ];
}

$sth->finish;

$size = @array;

setlogsock('unix');
openlog('SyncUser2RT', 'cons,ndelay,pid', 'local0');

for ( $i=0; $i < $size; $i++) {
	if ( $full_debug ) {
		print("id = ".$array[$i][0]."\n");
		print("Name = ".$array[$i][1]."\n");
		print("Password = ".$array[$i][2]."\n");
		print("EmailAddress = ".$array[$i][3]."\n");
		print("Organization = ".$array[$i][4]."\n");
		print("RealName = ".$array[$i][5]."\n");
		print("Lang = ".$array[$i][6]."\n");
		print("WorkPhone = ".$array[$i][7]."\n");
		print("MobilePhone = ".$array[$i][8]."\n");
		print("PagerPhone = ".$array[$i][9]."\n");
		print("Address1 = ".$array[$i][10]."\n");
		print("City = ".$array[$i][11]."\n");
		print("Zip = ".$array[$i][12]."\n");
		print("Country = ".$array[$i][13]."\n");
		print("ToCreate = ".$array[$i][14]."\n");
		print("RT_id = ".$array[$i][15]."\n") if (defined($array[$i][15]));
	} else 
	{

		if ( $array[$i][14] == 1 )
		{
	# User to add to RT
	 		%code = Insert2RT($array[$i][1], $array[$i][2], $array[$i][3], $array[$i][4], $array[$i][5], $array[$i][6], $array[$i][7], $array[$i][8], $array[$i][9], $array[$i][10], $array[$i][11], $array[$i][12], $array[$i][13] );
	
			if ( $code{'id'} != 0 ) {
				$update = "UPDATE TabUsers set RT_id = ".$code{'id'}.", RT_ToCreate = 0 WHERE IdUser = ".$array[$i][0];
				$syslog_msg_true = "User : ".$array[$i][1]." created in RT";
			} else {
				$syslog_msg_false = "User : ".$array[$i][1]." NOT created in RT";
			}
		} 
		elsif ( $array[$i][14] == 2 ) {
	# User to update in RT
	 		%code = Update2RT($array[$i][15], $array[$i][1], $array[$i][2], $array[$i][3], $array[$i][4], $array[$i][5], $array[$i][6], $array[$i][7], $array[$i][8], $array[$i][9], $array[$i][10], $array[$i][11], $array[$i][12], $array[$i][13] );
	
			if ( $code{'id'} ne '0' ) {
				$update = "UPDATE TabUsers SET RT_ToCreate = 0 WHERE RT_Name = '".$array[$i][1]."' AND IdUser = ".$array[$i][0];
				$syslog_msg_true = "User : ".$array[$i][1]." updated in RT";
			} else {
				$syslog_msg_false = "User : ".$array[$i][1]." NOT updated in RT";
			}
		} 
		elsif ( $array[$i][14] == 3 ) {
	# User to delete/inactive in RT
	 		%code = Delete2RT($array[$i][15], $array[$i][1] );
	
			$update = "DELETE FROM TabUsers WHERE RT_ToCreate = 3 AND RT_Name = '".$array[$i][1]."' AND IdUser = ".$array[$i][0];
			$syslog_msg_true = "User : ".$array[$i][1]." disabled in RT";
			$syslog_msg_false = "User : ".$array[$i][1]." NOT disabled in RT";
		}
	
		if ( $update ne "" && $dbh->do($update) )
		{
			syslog('notice', $syslog_msg_true);
		}
		else {
			syslog('warning', $syslog_msg_false);
		}
	}
}


$dbh->disconnect;
closelog();

1;



sub Insert2RT
{
	my ($Name, $Password, $EmailAddress, $Organization, $RealName, $Lang, $WorkPhone, $MobilePhone, $PagerPhone, $Address1, $City, $Zip, $Country) = @_;
		
	my $UserObj = new RT::User(RT::SystemUser);

	my ( $id, $msg ) = $UserObj->Create(
		Name => $Name,
		Comments => 'Created by SyncUser2RT',
		Password => $Password,
		EmailAddress => $EmailAddress,
		Organization => $Organization,
		RealName => $RealName,
		Privileged => 0,
		Lang => $Lang,
		WorkPhone => $WorkPhone,
		MobilePhone => $MobilePhone,
		PagerPhone => $PagerPhone,
		Address1 => $Address1,
		City => $City,
		Zip => $Zip,
		Country => $Country,
	);

	my %retour = (
		'id' => $id,
		'msg' => $msg
	);

	return %retour;
}


sub Update2RT
{
	my ($uid, $Name, $Password, $EmailAddress, $Organization, $RealName, $Lang, $WorkPhone, $MobilePhone, $PagerPhone, $Address1, $City, $Zip, $Country) = @_;

	my $UserObj = new RT::User(RT::SystemUser);
	$UserObj->Load($uid) || $UserObj->Load($Name) || die("Couldn't load user '$Name'");

	my $id = $UserObj->Id;
	my $msg;

	if ($id) {
# If we have a user to modify, lets try.
		my @fields = qw( Name EmailAddress Organization RealName Lang WorkPhone MobilePhone PagerPhone Address1 City Zip Country);
 
		my %ARGS;
		$ARGS{'Name'} = $Name;
		$ARGS{'EmailAddress'} = $EmailAddress;
		$ARGS{'Organization'} = $Organization;
		$ARGS{'RealName'} = $RealName;
		$ARGS{'Lang'} = $Lang;
		$ARGS{'WorkPhone'} = $WorkPhone;
		$ARGS{'MobilePhone'} = $MobilePhone;
		$ARGS{'PagerPhone'} = $PagerPhone;
		$ARGS{'Address1'} = $Address1;
		$ARGS{'City'} = $City;
		$ARGS{'Zip'} = $Zip;
		$ARGS{'Country'} = $Country;
 
		my @fieldresults = $UserObj->Update(
			AttributesRef => \@fields,
			Object => $UserObj,
			ARGSRef => \%ARGS
		);

# Must we update password too ?.
		if ( ($Password ne '') and (!$UserObj->IsPassword($Password))) {
			my ($code, $msg) = $UserObj->SetPassword($Password);
		}
	}

	my %retour = (
		'id' => $id,
		'msg' => $msg
	);

	return %retour;
	
}

sub Delete2RT
{
	my ($uid, $Name ) = @_;
 	
	my $UserObj = new RT::User(RT::SystemUser);
	$UserObj->Load($uid) || $UserObj->Load($Name) || die("Couldn't load user '$Name'");
 
	my $id = $UserObj->Id;
	my $msg;
 
	if ($id) {
# If we have a user to delete, lets try.
		my  ($code, $msg) = $UserObj->SetDisabled(1);
		if ( $code ) {
			my $time = time();
 # On renome le nom de l'utilisateur pour q'un meme login puisse exister
			my @fields = qw( Name EmailAddress );
			my %ARGS;
			$ARGS{'Name'} = $Name.$time;
			$ARGS{'EmailAddress'} = '';
 
			my @fieldresults = $UserObj->Update(
				AttributesRef => \@fields,
				Object => $UserObj,
				ARGSRef => \%ARGS
			);
		}
 	}

	my %retour = (
		'id' => $id,
		'msg' => $msg
	);

	return %retour;
	
}
