#!/usr/bin/perl -w
#
# unregisterClient.pl
#
# Copyright (C) 2011-2013 Cesnet z.s.p.o
#
# Use of this source is governed by a BSD-style license, see LICENSE file.

use strict;
use Getopt::Std;
use Switch;
use DBI;
use DBD::mysql;
use DateTime;
use Sys::Syslog qw(:DEFAULT setlogsock);
Sys::Syslog::setlogsock('unix');
use Carp;
use FindBin qw($RealBin $RealScript);
use lib "$FindBin::RealBin/../lib";
use WardenCommon;



################################################################################
#				VARIABLES
################################################################################
our $VERSION = "2.2";
my $etc = "$FindBin::RealBin/../etc";



################################################################################
#                               FUNCTIONS
################################################################################
sub usage {
  print "Usage: $RealScript [-h -i <client_id>]\n";
  exit 1;
}


sub help {
  print "$RealScript [-h -i <client_id>]\n";
  print "-h     print this text and exit\n";
  print "-i     client_id for unregistration\n";
  exit 0;
}



################################################################################
#                               MAIN
################################################################################
our ($opt_h, $opt_i);

if ($#ARGV == -1) {usage}

die usage unless getopts("i:h");
my $client_id	= $opt_i;
my $help        = $opt_h;

# catch help param
if ($help) {help}

# superuser controle
my $UID = $<;
if ($UID != 0) {WardenCommon::errMsg("You must be root for running this script!")}

# check parameters definition
if (!defined $client_id) {WardenCommon::errMsg("Parameter 'client_id' is not defined!")}

# read config file
my $conf_file = "$etc/warden-server.conf";
our $SYSLOG             = undef;
our $SYSLOG_VERBOSE     = undef;
our $SYSLOG_FACILITY    = undef;
our $DB_NAME            = undef;
our $DB_USER            = undef;
our $DB_PASS            = undef;
our $DB_HOST            = undef;
unless (do $conf_file) {
  die("Errors in config file '$conf_file': $@") if $@;
  die("Can't read config file '$conf_file': $!") unless defined $_;
  # if $_ defined, it's retvalue of last statement of conf, for which we don't care
}

# connect to DB
our $DBH = DBI->connect("DBI:mysql:database=$DB_NAME;host=$DB_HOST", $DB_USER, $DB_PASS, {RaiseError => 1, mysql_auto_reconnect => 1})
           || die "Could not connect to database: $DBH->errstr";

# check if receiver has been already registered
my $sth = $DBH->prepare("SELECT client_id, hostname, service, client_type, type FROM clients WHERE client_id = ? LIMIT 1;") or die "Cannot prepare statement: " . $DBH->errstr;
$sth->execute($client_id) or die "Cannot execute statement: " . $sth->errstr;
my ($id, $hostname, $service, $client_type, $type) = $sth->fetchrow();
my $warden_server = WardenCommon::trim(`hostname -f`);

# delete registered client
if (!defined $id) {
  WardenCommon::sendMsg($SYSLOG, $SYSLOG_VERBOSE, $SYSLOG_FACILITY, "err", "Attempt to delete unregister client (client_id: #$client_id)");
  WardenCommon::errMsg("Client (#$client_id) is not registered at $warden_server");
} else {
  if ($client_type eq 's') {
    $sth = $DBH->prepare("UPDATE clients SET valid = 'f' WHERE client_id = ?;") or die "Cannot prepare statement: " . $DBH->errstr;
    my $ret_val = $sth->execute($client_id) or die "Cannot execute statement: " . $sth->errstr;
    if ($ret_val == 1) {
      $sth = $DBH->prepare("UPDATE events SET valid = 'f' where hostname = ? AND service = ?;") or die "Cannot prepare statement: " . $DBH->errstr;
      $sth->execute($hostname, $service) or die "Cannot execute statement: " . $sth->errstr;
      WardenCommon::sendMsg($SYSLOG, $SYSLOG_VERBOSE, $SYSLOG_FACILITY, "info", "Sender '$hostname' [client_id: '$client_id', service: '$service'] was deleted and its data were invalidated from $warden_server");
      WardenCommon::succMsg("Unregistration of sender client (client_id: #$client_id) was SUCCESSFUL!!!");
    } else {
      WardenCommon::errMsg("Unregistration of sender client (client_id: #$client_id) FAILED!!!");
    }
  } else {
    $sth = $DBH->prepare("UPDATE clients SET valid = 'f' WHERE client_id = ?;") or die "Cannot prepare statement: " . $DBH->errstr;
    my $ret_val = $sth->execute($client_id) or die "Cannot execute statement: " . $sth->errstr;
    if ($ret_val == 1) {
      WardenCommon::sendMsg($SYSLOG, $SYSLOG_VERBOSE, $SYSLOG_FACILITY, "info", "Receiver '$hostname' [client_id: '$client_id', type: '$type'] was deleted from $warden_server");
      WardenCommon::succMsg("Unregistration of receiver client (client_id: #$client_id) was SUCCESSFUL!!!");
    } else {
      WardenCommon::errMsg("Unregistration of receiver client (client_id: #$client_id) FAILED!!!");
    }
  }
}