#!/usr/bin/perl
# 
# This tool is meant to be run from the command line and lets a user purge all information about a given host
# from the databases.
# 
# Exit codes;
# 0 = Normal exit.
# 1 = User's answer to which machine to purge was invalid.
# 2 = The passed-in (or selected) host UUID (no longer) exists.
# 3 = User did not confirm to proceed.
# 4 = Runaway loop detected.
# 

use strict;
use warnings;
use Anvil::Tools;
use Data::Dumper;
use Curses::UI;

my $THIS_FILE           =  ($0 =~ /^.*\/(.*)$/)[0];
my $running_directory   =  ($0 =~ /^(.*?)\/$THIS_FILE$/)[0];
if (($running_directory =~ /^\./) && ($ENV{PWD}))
{
	$running_directory =~ s/^\./$ENV{PWD}/;
}

# Turn off buffering so that the pinwheel will display while waiting for the SSH call(s) to complete.
$| = 1;

my $anvil = Anvil::Tools->new();

$anvil->Get->switches;
$anvil->Log->entry({source => $THIS_FILE, line => __LINE__, level => 2, secure => 0, key => "log_0115", variables => { program => $THIS_FILE }});

$anvil->Database->connect({debug => 3});
$anvil->Log->entry({source => $THIS_FILE, line => __LINE__, level => 2, secure => 0, key => "log_0132"});

# First, ask the user to select a host.
$anvil->data->{switches}{'host-uuid'} = "" if not defined $anvil->data->{switches}{'host-uuid'};
$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 2, list => { 'switches::host-uuid' => $anvil->data->{switches}{'host-uuid'} }});

$anvil->Database->get_hosts();

# Ask the user to pick a host.
pick_host($anvil);

# Ask the user to confirm.
confirm($anvil);

# If we're alive, purge.
purge($anvil);

$anvil->nice_exit({exit_code => 0});

#############################################################################################################
# Functions                                                                                                 #
#############################################################################################################

sub purge
{
	my ($anvil) = @_;
	
	# Read in all constraints and create a hash of what depends on what, then delete anything referencing
	# hosts without any further references. As each delete is done, delete it. Loop until all entries are
	# gone.
	
	# Load all the known tables in the DB.
	my $query = "SELECT schemaname||'.'||tablename AS table_name FROM pg_catalog.pg_tables WHERE schemaname = 'history' ORDER BY tablename ASC, schemaname ASC;";
	$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 2, list => { query => $query }});
	
	my $results = $anvil->Database->query({query => $query, source => $THIS_FILE, line => __LINE__});
	my $count   = @{$results};
	$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 3, list => { 
		results => $results, 
		count   => $count, 
	}});
	foreach my $row (@{$results})
	{
		my $table_name = $row->[0];
		$anvil->data->{sql}{history_tables}{$table_name} = 1;
		$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 3, list => { "sql::history_tables::${table_name}" => $anvil->data->{sql}{history_tables}{$table_name} }});
	}
	undef $query;
	undef $results;
	undef $count;
	
	### NOTE: Credit for this query goes to: 
	###       - https://stackoverflow.com/questions/1152260/postgres-sql-to-list-table-foreign-keys
	$query = "
SELECT
    tc.table_schema||'.'||tc.table_name AS table, 
    kcu.column_name, 
    ccu.table_schema||'.'||ccu.table_name AS foreign_table,
    ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
        ON tc.constraint_name = kcu.constraint_name
        AND tc.table_schema = kcu.table_schema
    JOIN information_schema.constraint_column_usage AS ccu
        ON ccu.constraint_name = tc.constraint_name
        AND ccu.table_schema = tc.table_schema
WHERE 
    tc.constraint_type = 'FOREIGN KEY'
AND 
    ccu.column_name = 'host_uuid'
;";
	$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 2, list => { query => $query }});
	
	$results = $anvil->Database->query({query => $query, source => $THIS_FILE, line => __LINE__});
	$count   = @{$results};
	$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 3, list => { 
		results => $results, 
		count   => $count, 
	}});
	foreach my $row (@{$results})
	{
		my $table_name           = $row->[0];
		my $column_name          = $row->[1];
		my $foreign_table_name   = $row->[2];
		my $foreign_column_name  = $row->[3];
		$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 3, list => { 
			's1:table_name'          => $table_name, 
			's2:column_name'         => $column_name, 
			's3:foreign_table_name'  => $foreign_table_name, 
			's4:foreign_column_name' => $foreign_column_name, 
		}});
		
		if (not exists $anvil->data->{sql}{table}{$table_name})
		{
			$anvil->data->{sql}{table}{$table_name}{column} = $column_name;
			$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 3, list => { "sql::table::${table_name}::column" => $anvil->data->{sql}{table}{$table_name}{column} }});
		}
		if (not exists $anvil->data->{sql}{table}{$foreign_table_name})
		{
			$anvil->data->{sql}{table}{$foreign_table_name}{column} = $foreign_column_name;
			$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 3, list => { "sql::table::${foreign_table_name}::column" => $anvil->data->{sql}{table}{$foreign_table_name}{column} }});
		}
		$anvil->data->{sql}{table}{$foreign_table_name}{referenced_by}{$table_name} = 1;
	}
	
	my $loops   = 20;
	my $loop    = 0;
	my $done    = 0;
	my $queries = [];
	until($done)
	{
		$loop++;
		foreach my $table_name (sort {$a cmp $b} keys %{$anvil->data->{sql}{table}})
		{
			my $count  = exists $anvil->data->{sql}{table}{$table_name}{referenced_by} ? keys %{$anvil->data->{sql}{table}{$table_name}{referenced_by}} : 0;
			#print "-- Table: [".$table_name."] is referenced by: [".$count."] foreign table(s);\n";
			if (not $count)
			{
				# If there is a corresponding history table, delete it as well.
				my $column        =  $anvil->data->{sql}{table}{$table_name}{column};
				my $history_table =  $table_name;
				   $history_table =~ s/^public\./history\./;
				if (exists $anvil->data->{sql}{history_tables}{$history_table})
				{
					push @{$queries}, "DELETE FROM ".$history_table." WHERE ".$column." = ".$anvil->Database->quote($anvil->data->{switches}{'host-uuid'}).";";
				}
				
				# Now delete the public table entries.
				push @{$queries}, "DELETE FROM ".$table_name." WHERE ".$column." = ".$anvil->Database->quote($anvil->data->{switches}{'host-uuid'}).";";
				
				foreach my $foreign_table_name (sort {$a cmp $b} keys %{$anvil->data->{sql}{table}})
				{
					if (exists $anvil->data->{sql}{table}{$foreign_table_name}{referenced_by}{$table_name})
					{
						#print "-- Deleting: [".$foreign_table_name."] reference to: [".$table_name."]\n";
						delete $anvil->data->{sql}{table}{$foreign_table_name}{referenced_by}{$table_name};
					}
				}
				#print "-- Deleting hash entry for: [".$table_name."]\n";
				delete $anvil->data->{sql}{table}{$table_name};
			}
		}
		
		my $remaining = keys %{$anvil->data->{sql}{table}};
		$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 2, list => { remaining => $remaining }});
		if (not $remaining)
		{
			$done = 1;
		}
		elsif ($loop > $loops)
		{
			print "Run-away loop detected, aborting!\n";
			$anvil->nice_exit({exit_code => 4});
		}
	}
	
	# Do the deed.
	$anvil->Database->write({debug => 2, query => $queries, source => $THIS_FILE, line => __LINE__});
	my $host_uuid = $anvil->data->{switches}{'host-uuid'};
	print $anvil->Words->string({key => "message_0176", variables => { host_name => $anvil->data->{hosts}{host_uuid}{$host_uuid}{host_name} }})."\n";
	
	return(0);
}

sub confirm
{
	my ($anvil) = @_;
	
	# Normalize -y
	$anvil->data->{switches}{'y'}   = "" if not defined $anvil->data->{switches}{'y'};
	$anvil->data->{switches}{'yes'} = "" if not defined $anvil->data->{switches}{'yes'};
	$anvil->data->{switches}{'Y'}   = "" if not defined $anvil->data->{switches}{'Y'};
	$anvil->data->{switches}{'Yes'} = "" if not defined $anvil->data->{switches}{'Yes'};
	$anvil->data->{switches}{'YES'} = "" if not defined $anvil->data->{switches}{'YES'};
	if (not $anvil->data->{switches}{'y'})
	{
		if    ($anvil->data->{switches}{'yes'}) { $anvil->data->{switches}{'y'} = $anvil->data->{switches}{'yes'}; }
		elsif ($anvil->data->{switches}{'Y'})   { $anvil->data->{switches}{'y'} = $anvil->data->{switches}{'Y'}; }
		elsif ($anvil->data->{switches}{'Yes'}) { $anvil->data->{switches}{'y'} = $anvil->data->{switches}{'Yes'}; }
		elsif ($anvil->data->{switches}{'YES'}) { $anvil->data->{switches}{'y'} = $anvil->data->{switches}{'YES'}; }
	}
	
	# Ask to confirm, is sane and not -y
	my $host_uuid = $anvil->data->{switches}{'host-uuid'};
	if (not exists $anvil->data->{hosts}{host_uuid}{$host_uuid}{host_name})
	{
		print $anvil->Words->string({key => "error_0131", variables => { host_uuid => $host_uuid }})."\n\n";
		$anvil->nice_exit({exit_code => 2});
	}
	else
	{
		print $anvil->Words->string({key => "message_0172"})."\n\n";
		print $anvil->Words->string({key => "message_0173", variables => { 
			host_name => $anvil->data->{hosts}{host_uuid}{$host_uuid}{host_name},
			host_uuid => $host_uuid,
		}})."\n";
		$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 3, list => { 'switches::y' => $anvil->data->{switches}{'y'} }});
		if ($anvil->data->{switches}{'y'} eq "#!SET!#")
		{
			# Already confirmed.
			print $anvil->Words->string({key => "message_0023"})."\n\n";
			return(0);
		}
		print $anvil->Words->string({key => "message_0021"})." ";
		chomp(my $answer = <STDIN>);
		
		if ($answer =~ /^y/i)
		{
			# Proceed.
			print $anvil->Words->string({key => "message_0175"})."\n";
		}
		else
		{
			# Abort.
			print $anvil->Words->string({key => "message_0022"})."\n";
			$anvil->nice_exit({exit_code => 3});
		}
	}
	
	return(0);
}

sub pick_host
{
	my ($anvil) = @_;
	
	return(0) if $anvil->data->{switches}{'host-uuid'};
	
	# Get a list of hosts
	my $i           = 1;
	my $select      = {};
	my $host_length = 0;
	my $type_length = 0;
	foreach my $host_name (sort {$a cmp $b} keys %{$anvil->data->{sys}{hosts}{by_name}})
	{
		my $host_uuid  =         $anvil->data->{sys}{hosts}{by_name}{$host_name};
		my $host_type  =         $anvil->data->{hosts}{host_uuid}{$host_uuid}{host_type};
		my $anvil_name = defined $anvil->data->{hosts}{host_uuid}{$host_uuid}{anvil_name} ? $anvil->data->{hosts}{host_uuid}{$host_uuid}{anvil_name} : "";
		my $say_type  = $anvil->Words->string({key => "brand_0009"});
		if    ($host_type eq "striker") { $say_type = $anvil->Words->string({key => "brand_0003"}); }
		elsif ($host_type eq "node")    { $say_type = $anvil->Words->string({key => "brand_0007"}); }
		elsif ($host_type eq "dr")      { $say_type = $anvil->Words->string({key => "brand_0008"}); }
		
		if (length($host_name) > $host_length) { $host_length = length($host_name); }
		if (length($say_type)  > $type_length) { $type_length = length($say_type);  }
		
		# This is used to build the menu.
		$select->{$i}{host_uuid}  = $host_uuid;
		$select->{$i}{host_name}  = $host_name;
		$select->{$i}{host_type}  = $host_type;
		$select->{$i}{say_type}   = $say_type;
		$select->{$i}{anvil_name} = $anvil_name;
		$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 3, list => { 
			"${i}::host_uuid"  => $select->{$i}{host_uuid},
			"${i}::host_name"  => $select->{$i}{host_name},
			"${i}::host_type"  => $select->{$i}{host_type},
			"${i}::anvil_name" => $select->{$i}{anvil_name},
		}});
		$i++;
	}
	
	my $pad = $i > 9 ? 2 : 1;
	print $anvil->Words->string({key => "message_0169"})."\n\n";
	foreach my $i (sort {$a cmp $b} keys %{$select})
	{
		print " ".$anvil->Words->string({key => "message_0170", variables => {
			key       => sprintf("%".$pad."s", $i),
			type      => sprintf("%-".$type_length."s", $select->{$i}{say_type}),
			host_name => sprintf("%-".$host_length."s", $select->{$i}{host_name}),
			host_uuid => $select->{$i}{host_uuid},
		}})."\n";
	}
	print "\n".$anvil->Words->string({key => "message_0171"})." ";
	
	chomp(my $answer = <STDIN>);
	
	if (not exists $select->{$answer}{host_name})
	{
		print "\n".$anvil->Words->string({key => "error_0130", variables => { answer => $answer }})."\n\n";
		$anvil->nice_exit({exit_code => 1});
	}
	else
	{
		print "\n";
		$anvil->data->{switches}{'host-uuid'} = $select->{$answer}{host_uuid};
	}
	
	return(0);
}
