#!/usr/bin/perl

package main;
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

use English;
use Getopt::Long;
use DBI;
use Schema;

use YAML;
use YAML qw(LoadFile);
use DBIx::Class::Schema::Loader qw/make_schema_at/;


#TEMPLATE TO BE CHANGED BY THE USER
#################################################################################################
# Environment: If not set by command-line, the below variable setting will take effect. 
my $default_environment = '';
if ($default_environment eq "") {
	$default_environment = $ENV{'MOJO_MODE'};
}
#################################################################################################
#DONE TEMPLATE TO BE CHANGED BY THE USER

my $usage = "\n"
	. "Usage:  $PROGRAM_NAME (--assign-user | --list-root-tenants) [--env <environment>] [--tenant-name <tenant-name>] username1 [username2 ...]\t\n\n"
	. "Examples:  $PROGRAM_NAME --assign-user admin1\n"
	. "           $PROGRAM_NAME --list-root-tenants --env production\n\n"
	. "Purpose:  This script allows the assignment a user tenant.\n"
	. "          It is required in order to set the tenancy of the initial admin user of a root tenant\n"
	. "          (If no such user exists the tenant practically cannot be used).\n"
	. "          It additionally can provide a list of all root tenants.\n\n"
	. "Operations:   \n"
	. "assign-user  - Assign a user to tenant acording to below options.\n"
	. "list-root-tenants  - list all root tenants.\n\n"
	. "Options:   \n"
	. "env  - The environment (development|test|production|integration) to execute the operation on.\n"
	. "       If not set, '$default_environment' is used (value is 'MOJO_MODE' env var dependent).\n"
	. "tenant-name  - The tenant name of the tenant to assign the user to.\n"
	. "               If not set, use the single root tenant defined.\n"
	. "               If set, and no tenant exists, create the tenant as a root tenant.\n\n"
	. "Arguments:   \n"
	. "List of usernames of users to be assign to the tenant.\n"
	. "\n\n";


#parameters retrival
my $help = 0;
my $list_root_tenants = 0;
my $assign_user = 0;
my $environment = '';
my $tenant_name = '';

GetOptions( "help|?", \$help, "list-root-tenants", \$list_root_tenants, "assign-user", \$assign_user, "env:s", \$environment, "tenant-name:s", \$tenant_name );

if ($help || (!$list_root_tenants && !$assign_user)) {
	print $usage and exit(0);
}

# get environment name
if ($environment eq "") {
	$environment =  $default_environment;
}
if ($environment eq "") {
	print STDERR $usage;
	print STDERR "No environment specified!\n" and exit(1);
}
$ENV{'MOJO_MODE'} = $environment;

#DB connection
my $dbh    = Schema->database_handle;
my $schema = Schema->connect_to_database;

if ($list_root_tenants) {
	my $tenants = $schema->resultset('Tenant')->search({ parent_id => undef });
	while ( my $row = $tenants->next ) {
		my $tenant_id =  $row->id;
		my $tenant_name =  $row->name;
		print "ID: $tenant_id NAME: $tenant_name\n";
	}
	exit(0);
}

# assign-user operation

if (!@ARGV){
	print STDERR $usage;
	print STDERR "No username was specified!\n" and exit(1);
}

my $root_tenants = $schema->resultset('Tenant')->search({ parent_id => undef });
	
# get tenant name
if ($tenant_name eq "") {
	#find the root tenant	
	if ($root_tenants->count > 1) {
		print STDERR "More than 1 root tenants, please specify tenant name\n" and exit(1);
	}
	my $tenant = $root_tenants->single;
	if (!defined($tenant)) {
		print STDERR "No root tenant, please specify tenant name one for creation\n" and exit(1);
	}
	$tenant_name = $tenant->name;
}
	
# Create tenant if needed
my $tenant = $schema->resultset('Tenant')->search( {name =>  $tenant_name} )->single;
if (!defined($tenant)){
	if ($root_tenants->count == 0){
		#no tenants, lest create a tenant as requested
		my $tenant_values = {
				name => $tenant_name,
				active => 1,
				parent_id => undef
				};
		
		my $insert = $schema->resultset('Tenant')->create($tenant_values)->insert();
		if (! $insert) {
			print STDERR "Failed creating tenant '$tenant_name'!\n" and exit(1);
		}
		print STDERR "Tenant '$tenant_name' was created.\n";
		$tenant = $schema->resultset('Tenant')->search( {name =>  $tenant_name} )->single;
	}
	else {
		print STDERR "Tenant '$tenant_name' does not exists.\n" and exit(1);
	}
}


#update the user tenancy
my $rc = 0;
foreach $user_name (@ARGV) {
	my $user_data = $schema->resultset('TmUser')->search({ username => $user_name })->single;
	if (!defined($user_data)) {
		print STDERR "User '$user_name' does not exists!\n";
		$rc = 1;
		next;
	}
	
	my $user = $schema->resultset('TmUser')->find( { id => $user_data->id } );
	my $rc = $user->update({tenant_id=>$tenant->id});

	if (! $rc) {
		print STDERR "Failed setting tenant '$tenant_name' to user '$user_name'!\n";
		$rc = 1;
	}
	print STDERR "User '$user_name' tenancy was set.\n";
}

exit($rc);
