#!/usr/bin/perl
# 
# This calls 'osinfo-query os' and parses the list of OSes reported by it, formatting them into words.xml 
# entries. Any entries found not already in words.xml are printed to STDOUT.
# 
 
use strict;
use warnings;
use Anvil::Tools;
use Data::Dumper;

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();

# Read switches (target ([user@]host[:port]) and the file with the target's password.
$anvil->Get->switches;
$anvil->Log->entry({source => $THIS_FILE, line => __LINE__, level => 2, key => "log_0115", variables => { program => $THIS_FILE }});

my $words_file = $anvil->data->{path}{words}{'words.xml'};
my $language   = $anvil->Words->language;
my $shell_call = $anvil->data->{path}{exe}{'osinfo-query'}." os";
$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 2, list => { shell_call => $shell_call }});

my ($output, $return_code) = $anvil->System->call({shell_call => $shell_call});
$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 2, list => { 
	output      => $output,
	return_code => $return_code,
}});

foreach my $line (split/\n/, $output)
{
	$line = $anvil->Words->clean_spaces({string => $line});
	$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 2, list => { line => $line }});
	
	next if $line =~ /Short ID/;
	next if $line =~ /----------------------/;
	my ($os_code, $os_name) = ($line =~ /^(.*?) \| (.*?) \|/);
	$anvil->Log->variables({source => $THIS_FILE, line => __LINE__, level => 2, list => { 
		's1:os_code' => $os_code,
		's2:os_name' => $os_name, 
	}});
	
	my $os_key = "os_list_".$os_code;
	if ((not exists $anvil->data->{words}{$words_file}{language}{$language}{key}{$os_key}) or (not $anvil->data->{words}{$words_file}{language}{$language}{key}{$os_key}{content}))
	{
		# Print already known.
		print "\t\t<key name=\"".$os_key."\"><![CDATA[".$os_name."]]></key>\n";
	}
}

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