#!/usr/bin/perl
$Version  = 'SCST DB Configurator v0.51.1';

# Configures SCST
#
# Written by Mark R. Buechler 12/07/04

sub usage
  {
    die <<"EndUsage";
$Version

Usage:
General Operations
     -config <config>     : Configure SCST given the specified configuration file.
     -check               : Check database configuration against current configuration.

Options
     -ForceConfig         : Force all confuration changes, even deletions (DANGER!).

Debugging (limited support)
     -debug               : Debug mode - don\'t do anything destructive.
     
Examples:
     Configure SCST:
       scst_db config scst_db.conf

EndUsage
  }

use SCST::SCST;
use Getopt::Long;
use IO::Handle;
use IO::File;
use DBI;
use POSIX;
use strict;

my $_DEF_CONFIG_ = '/etc/scst_db.conf';

my $TRUE  = 1;
my $FALSE = 0;

my $_MAX_LUNS_      = 255;
my $_DEFAULT_GROUP_ = 'Default';

my $_MDADM_  = '/sbin/mdadm';
my $_MDSTAT_ = '/proc/mdstat';
my $_MD_DEV_ = '/dev/';

my $SCST;
my $DEVICES;
my %USERS;
my %ASSIGNMENTS;
my %HANDLERS;
my %GROUPS;
my $_DEBUG_;

my %MD_DEVICES;

my %_HANDLER_MAP_ = ('cdrom' => $SCST::SCST::CDROM_TYPE,
		     'changer' => $SCST::SCST::CHANGER_TYPE,
		     'disk' => $SCST::SCST::DISK_TYPE,
		     'vdisk' => $SCST::SCST::VDISK_TYPE,
		     'vcdrom' => $SCST::SCST::VCDROM_TYPE,
		     'disk_perf' => $SCST::SCST::DISKPERF_TYPE,
		     'modisk' => $SCST::SCST::MODISK_TYPE,
		     'modisk_perf' => $SCST::SCST::MODISKPERF_TYPE,
		     'tape' => $SCST::SCST::TAPE_TYPE,
		     'tape_perf' => $SCST::SCST::TAPEPERF_TYPE);
		     
my %_REVERSE_MAP_ = ($SCST::SCST::CDROM_TYPE => 'cdrom',
		     $SCST::SCST::CHANGER_TYPE => 'changer',
		     $SCST::SCST::DISK_TYPE => 'disk',
		     $SCST::SCST::VDISK_TYPE => 'vdisk',
		     $SCST::SCST::VCDROM_TYPE => 'vcdrom',
		     $SCST::SCST::DISKPERF_TYPE => 'disk_perf',
		     $SCST::SCST::MODISK_TYPE => 'modisk',
		     $SCST::SCST::MODISKPERF_TYPE => 'modisk_perf',
		     $SCST::SCST::TAPE_TYPE => 'tape',
		     $SCST::SCST::TAPEPERF_TYPE => 'tape_perf');

$SIG{INT} = \&commitSuicide;

POSIX::setsid();

&main();

sub getArgs {
	my $applyConfig;
	my $checkConfig;
	my $forceConfig;

	my $p = new Getopt::Long::Parser;

	if (!$p->getoptions('config:s'          => \$applyConfig,
			    'check'		=> \$checkConfig,
			    'ForceConfig'	=> \$forceConfig,
			    'debug'             => \$_DEBUG_)) {
		&usage();
	}

	$applyConfig = $_DEF_CONFIG_ if (defined($applyConfig) && !$applyConfig);
	$forceConfig = $TRUE if (defined($forceConfig));

	return ($applyConfig, $checkConfig, $forceConfig);
}

sub main {
	my $rc;

	STDOUT->autoflush(1);

	# We need to run as root
	if ( $> ) {die("This program must run as root.\n");}

	my ($config, $check, $force) = getArgs();

	$SCST = new SCST::SCST($_DEBUG_);

	readCurrentConfig();
	scanDevices();

	SWITCH: {
		$config && do {
			$rc = applyConfiguration($config, $force, $check);
			last SWITCH;
		};

		print "No valid operations specified.\n";
		usage();
		exit $TRUE;
	}

	print "All done.\n";

	exit $rc;
}

sub readCurrentConfig {
	print "Collecting current configuration.. ";

	my $eHandlers = $SCST->handlers();

	foreach my $handler (@{$eHandlers}) {
		$HANDLERS{$handler}++; # For quick lookups
	}

	$DEVICES = $SCST->devices();
	my $_eGroups = $SCST->groups();

	foreach my $group (@{$_eGroups}) {
		$GROUPS{$group}++; # For quick lookups
		$ASSIGNMENTS{$group} = $SCST->groupDevices($group);
		my $eUsers = $SCST->users($group);

		foreach my $user (@{$eUsers}) {
			$USERS{$group}->{$user}++; # For quick lookups
		}
	}

	print "done.\n";
}

sub scanDevices {
	my $ch = new IO::Handle;
	
	print "Scanning available system devices.. ";
	
	my $mdstat = new IO::File $_MDSTAT_, O_RDONLY;
	
	die("FATAL: Unable to gather a list of available md devices.\n") if (!$mdstat);
	
	while (my $line = <$mdstat>) {
		if ($line =~ /^md/) {
			my($md, undef) = split(/\:/, $line);
			$md = cleanupString($md);
			$md = $_MD_DEV_.$md;

			open $ch, "$_MDADM_ --detail $md -b|" or 
			  die("FATAL: Unable to gather information for md device $md.\n");
			
			my $buffer = <$ch>;
			chomp $buffer;
			
			close $ch;

			my(undef, $uuid_t) = split(/UUID\=/, $buffer);
			$uuid_t = cleanupString($uuid_t);

			$MD_DEVICES{$uuid_t} = $md;
		}
	}
	
	print "done.\n";
}

sub applyConfiguration {
	my $confile = shift;
	my $force = shift;
	my $check = shift;
	my $config = readConfig($confile);
	my $errs;
	my $changes = 0;

	my $database = $$config{'DATABASE'}->{'default'}->{'NAME'};
	my $user     = $$config{'DATABASE'}->{'default'}->{'USERNAME'};
	my $password = $$config{'DATABASE'}->{'default'}->{'PASSWORD'};
	my $hostname = $$config{'DATABASE'}->{'default'}->{'HOST'};
	
	my $db = DBI->connect("DBI:mysql:database=$database;host=$hostname", "$user", "$password");
	
	my $sth = $db->prepare("SELECT device_id, device_path, options, blocksize, type_id, perf_id, md_uuid, handler_name ".
	                       "FROM devices, scst_handlers ".
			       "WHERE devices.scst_handlr_id = scst_handlers.scst_handlr_id ".
			       "ORDER BY device_id");
	die("FATAL: Unable to obtain list of devices: ".$sth->errstr."\n") if (!$sth->execute());
	
	# Open new devices and assign them to handlers..
	while (my $ref = $sth->fetchrow_hashref()) {
		if (!$HANDLERS{$_HANDLER_MAP_{$ref->{'handler_name'}}}) {
			print "WARNING: Handler '".$ref->{'handler_name'}."' does not exist.\n";
			$errs += 1;
			next;
		}
		
		my $vname = translateDeviceName($ref->{'device_id'}, $ref->{'type_id'}, $ref->{'perf_id'});

		next if (defined($$DEVICES{$vname}));

		my $options = $ref->{'options'};
		$options =~ s/\s+//; $options =~ s/\|/,/;

		if ($ref->{'md_uuid'}) {
			print "Using UUID for device ".$ref->{'device_id'}." ($vname).\n";

			my $handler = $ref->{'handler_name'};
			my $uuid = findMDDevice($ref->{'md_uuid'});
			my $blocksize = $ref->{'blocksize'};

			$changes++;

			if ($check) {
				print "\t-> New device '$handler:$vname', UUID: '$uuid', ".
				  "Options: '$options' Blocksize: $blocksize.\n";
			} else {
				$errs += addDevice($handler, $vname, $uuid, $options, $blocksize);
			}
		} elsif ($ref->{'device_path'}) {
			print "Using path for device ".$ref->{'device_id'}." ($vname).\n";

			my $handler = $ref->{'handler_name'};
			my $path = $ref->{'device_path'};
			my $blocksize = $ref->{'blocksize'};

			$changes++;

			if ($check) {
				print "\t-> New device '$handler:$vname', Path: '$path', ".
				  "Options: '$options', Blocksize: $blocksize.\n";
			} else {
				$errs += addDevice($handler, $vname, $path, $options, $blocksize);
			}
		} else {
			print "FATAL: No UUID or path configured for device ".$ref->{'device_id'}." ($vname).\n";
			$errs += 1;
			next;
		}
	}

	my $sth = $db->prepare("SELECT group_id, group_name FROM security_groups");
	die("FATAL: Unable to obtain list of groups: ".$sth->errstr."\n") if (!$sth->execute());
	
	# Create new groups and add users..
	while (my $ref = $sth->fetchrow_hashref()) {
		if (!defined($GROUPS{$ref->{'group_name'}})) {
			my $group = $ref->{'group_name'};

			$changes++;

			if ($check) {
				print "\t-> New group definition '$group'.\n";
			} else {
				$errs += addGroup($group);
			}
		}
	}

	my $sth = $db->prepare("SELECT group_name, user_id ".
			       "FROM group_users, security_groups ".
			       "WHERE security_groups.group_id = group_users.group_id");
	die("FATAL: Unable to obtain list of users: ".$sth->errstr."\n") if (!$sth->execute());

	while (my $ref = $sth->fetchrow_hashref()) {
		if (!defined($USERS{$ref->{'group_name'}}->{$ref->{'user_id'}})) {
			my $group = $ref->{'group_name'};
			my $user = $ref->{'user_id'};

			$changes++;

			if ($check) {
				print "\t-> New user definition '$user' for group '$group'.\n";
			} else {
				$errs += addUser($group, $user);
			}
		}
	}

	my $sth_a = $db->prepare("SELECT device_id, type_id, group_name, host_id, target_id, target_lun ".
				 "FROM assignments, security_groups ".
				 "WHERE assignments.group_id = security_groups.group_id");
	die("FATAL: Unable to obtain list of assignments: ".$sth_a->errstr."\n") if (!$sth_a->execute());

	# Assign new devices to groups..
	while (my $ref_a = $sth_a->fetchrow_hashref()) {
		if (!defined($GROUPS{$ref_a->{'group_name'}})) {
			print "WARNING: Unable to assign to non-existant group '".$ref_a->{'group_name'}."'.\n";
			$errs += 1;
			next;
		}

		my $sth_d = $db->prepare("SELECT type_id, perf_id FROM devices ".
					 "WHERE device_id = ".$ref_a->{'device_id'}." ".
					 "AND type_id = '".$ref_a->{'type_id'}."'");
		die("FATAL: Unable to obtain list of device information: ".$sth_d->errstr."\n") if (!$sth_d->execute());
		
		my $ref_d = $sth_d->fetchrow_hashref();
		
		my $vname = translateDeviceName($ref_a->{'device_id'}, $ref_d->{'type_id'}, $ref_d->{'perf_id'});

		my $_assignments = $ASSIGNMENTS{$ref_a->{'group_name'}};
		next if (defined($$_assignments{$vname}));

		my $group = $ref_a->{'group_name'};
		my $lun = $ref_a->{'target_lun'};

		$changes++;

		if ($check) {
			print "\t-> New device assignment '$vname' for group '$group' at LUN $lun.\n";
		} else {
			$errs += assignDevice($group, $vname, $lun);
		}
	}

	print "Encountered $errs error(s) while processing.\n" if ($errs);

	undef $db;

	if ($check) {
		print "Configuration checked, $changes difference(s) found with current configuation.\n";
	} else {
		print "Configuration applied.\n";
	}

	return $TRUE if ($errs);
	return $FALSE;
}

sub addDevice {
	my $handler = shift;
	my $device = shift;
	my $path = shift;
	my $options = shift;

	$options =~ s/\,/ /;

	my $_handler = $_HANDLER_MAP_{$handler};

	if (defined($$DEVICES{$device})) {
		print "WARNING: Device '$device' already defined.\n";
		return $TRUE;
	}

	print "Opening virtual device '$device' at path '$path' using handler '$handler'..\n";

	if ($SCST->openDevice($_handler, $device, $path, $options)) {
		print "WARNING: Failed to open virtual device '$device' at path '$path' (Options: $options).\n";
		return $TRUE;
	}

	$$DEVICES{$device} = $_handler;

	return $FALSE;
}

sub addGroup {
	my $group = shift;

	if (defined($GROUPS{$group})) {
		print "WARNING: Group '$group' already exists.\n";
		return $TRUE;
	}

	print "Creating security group '$group'..\n";

	if ($SCST->addGroup($group)) {
		print "WARNING: Failed to create security group '$group'.\n";
		return $TRUE;
	}

	$GROUPS{$group}++;

	return $FALSE;
}

sub addUser {
	my $group = shift;
	my $user = shift;

	if (!defined($GROUPS{$group})) {
		print "WARNING: Failed to add user '$user' to group '$group', group does not exist.\n";
		return $TRUE;
	}

	if (defined($USERS{$group}->{$user})) {
		print "WARNING: User '$user' already exists in security group '$group'.\n";
		return $TRUE;
	}

	print "Adding user '$user' to security group '$group'..\n";

	if ($SCST->addUser($user, $group)) {
		print "WARNING: Failed to add user '$user' to security group '$group'.\n";
		return $TRUE;
	}

	$USERS{$group}->{$user}++;

	return $FALSE;
}

sub assignDevice {
	my $group = shift;
	my $device = shift;
	my $lun = shift;
	my %allLuns;

	# Put luns into something easier to parse..
	foreach my $_group (keys %ASSIGNMENTS) {
		my $_gAssigns = $ASSIGNMENTS{$_group};

		foreach my $_device (keys %{$_gAssigns}) {
			@{$allLuns{$_group}}[$$_gAssigns{$_device}] = $_device;
		}
	}

	# Use the next available LUN if none specified
	if ($lun !~ /\d+/) {
		$lun = ($#{$allLuns{$group}} + 1);
		if ($lun > $_MAX_LUNS_) {
			print "ERROR: Unable to use next available LUN of $lun, lun out of range.\n";
			return $TRUE;
		}

		print "Device '$device': Using next available LUN of $lun for group '$group'.\n";
	}
			
	if (($lun < 0) || ($lun > $_MAX_LUNS_)) {
		print "ERROR: Unable to assign device '$device', lun '$lun' is out of range.\n";
		return $TRUE;
	}

	if (!defined($$DEVICES{$device})) {
		print "WARNING: Unable to assign non-existant device '$device' to group '$group'.\n";
		return $TRUE;
	}

	if (@{$allLuns{$group}}[$lun]) {
		print "ERROR: Device '$device': Lun '$lun' is already assigned to device '".@{$allLuns{$group}}[$lun]."'.\n";
		return $TRUE;
	}

	print "Assign virtual device '$device' to group '$group' at LUN '$lun'..\n";

	if ($SCST->assignDeviceToGroup($device, $group, $lun)) {
		print "WARNING: Failed to assign device '$device' to group '$group'.\n";
		return $TRUE;
	}

	if (!defined($ASSIGNMENTS{$group})) {
		my %assignments_t;
		$ASSIGNMENTS{$group} = \%assignments_t;
	}

	my $_assignments = $ASSIGNMENTS{$group};

	$$_assignments{$device} = $lun; 

	return $FALSE;
}

sub readConfig {
	my $confile = shift;
	my %config;
	my $section;
	my $arg;

	my $io = new IO::File $confile, O_RDONLY;

	die("FATAL: Unable to open specified configuration file $confile: $!\n") if (!$io);

	while (my $line = <$io>) {
		($line, undef) = split(/\#/, $line, 2);
		$line = cleanupString($line);

		if ($line =~ /^\[(.*)\]$/) {
			($section, $arg) = split(/\s+/, $1, 2);
		} elsif ($section && $arg && $line) {
			my($parameter, $value) = split(/\s+/, $line, 2);
			$config{$section}->{$arg}->{$parameter} = $value;
		}
	}

	close $io;

	return \%config;
}

sub findMDDevice {
	my $uuid = shift;

	return $MD_DEVICES{$uuid};
}

sub translateDeviceName {
	my $device_id = shift;
	my $type_id = shift;
	my $perf_id = shift;
	
	my $device_id = sprintf("%lx", $device_id);
	my $device_id_t = $device_id;

	for (my $t = length($device_id); $t <= 2; $t++) {
		$device_id_t = "0$device_id_t";
	}

	$device_id = $device_id_t;

	return $type_id.$perf_id.$device_id;
}

sub cleanupString {
	my $string = shift;

	$string =~ s/^\s+//;
	$string =~ s/\s+$//;

	return $string;
}

# Hey! Stop that!
sub commitSuicide {
	print "\n\nBut I haven\'t finished yet!\n";
	exit 1;
}
