#!/usr/bin/env perl

use warnings;
use strict;

# v1.1.0 20161022 RWR
# use library sysinfoconf.pm for loading, editing and displaying config
#
# v1.2.0 20190108 RWR
# added UUID
#
# v1.3.0 20191107 RWR
# changed the screen to allow the user to see most of the values and decide what to edit
# then write the results.
# also, parameters are passed that allow the import of a file in old conf format
#
# v1.3.1 20191112 RWR
# Fixed showEntry() to set value to empty string if it is null 

use Getopt::Long;


our $VERSION = '1.3.1';

# find our location and use it for searching for libraries
BEGIN {
   use FindBin;
   use File::Spec;
   use lib File::Spec->catdir($FindBin::Bin);
}

use sysinfoconf; # a library of shared routines with install.pl

my $config;

sub findSendEmail {
   my $currentLocation = shift;
   my @possibles = ( 
            '/usr/local/opt/sendEmail/sendEmail',
            '/usr/local/opt/sendEmail/sendEmail.pl',
            '/opt/sendEmail/sendEmail', 
            '/opt/sendEmail/sendEmail.pl' 
            );
   return $currentLocation if ( $currentLocation && -x $currentLocation );
   # well, we didn't find it, so look around some more
   # Look through the possibles
   foreach my $current ( @possibles ) {
      return $current if -x $current;
   }
   if ( &yesno( "You are asking for sendEmail, but I don't see it on the system\nWould you like me to automatically download and install" ) ) {
      my $path = `perl getSendEmail.pl`;
      chomp $path;
      return $path;
   }
   return '';
}

sub userConfirmation {
   my $config = shift;
   
}

sub setUpTransport {
   my ($priority, $transport, $fields, $type ) = @_;
   $priority = getAnswer( 'Priority', $priority );
   $$transport{'sendScript'} = $$fields{'sendScript'} unless $$transport{'sendScript'};
   $$transport{'name'} = $type unless $$transport{'name'};
   my $allKeys = $$fields{'keys'};
   foreach my $key ( @$allKeys ) {
      if ( $key eq 'sendEmailScriptLocation' && ! -e $$transport{$key} ) {
         my $temp = &findSendEmail( $$transport{$key} );
         $$transport{$key} = $temp if $temp;
      }
      $$transport{$key} = &getAnswer( "$key ", $$transport{$key} ? $$transport{$key} : '' );
   }
   return ( $priority, $transport );
}

sub showAllTransports {
   foreach my $priority ( sort { $a <=> $b } keys %$transports ) {
      print '='x40 . "\n";
      &showTransports( $priority, $$transports{ $priority } );
      print '='x40 . "\n";
   }
}   

sub showTransports {
   my ( $priority,$thisOne )  = @_;
   print $$thisOne{'name'} . " has priority $priority\n";
   foreach my $key ( sort keys %$thisOne ) {
      next if $key =~ m/^-.*-$/;
      print "$key = $$thisOne{$key}\n";
   }
}

sub doTransports {
   my ( $transports ) = @_;
   
   foreach my $priority ( sort { $a <=> $b } keys %$transports ) {
      if ( &yesno( $$transports{$priority}{'name'} . " has a priority of $priority, edit it?") ) {
         #print Dumper( $sendTypes{$$transports{$priority}{'name'}} );
         #die;
         my ( $newpriority,$temp ) = &setUpTransport( $priority, $$transports{$priority}, $sendTypes{$$transports{$priority}{'name'}} );
         if ( $newpriority != $priority ) {
            delete $$transports{$priority};
            $priority = $newpriority;
         }
         $$transports{$priority} = $temp;
      } # if
   }

   foreach my $priority ( sort { $a <=> $b } keys %$transports ) {
      print '='x40 . "\n";
      &showTransports( $priority, $$transports{ $priority } );
      print '='x40 . "\n";
   }

   while ( &yesno( "Would you like to add any other transport mechanisms?" ) ) {
      my $newType = &getAnswer( 'Type of Transport? ', keys %sendTypes );
      my ( $priority,$temp ) = &setUpTransport( 99, {}, $sendTypes{$newType}, $newType );
      $$transports{$priority} = $temp;
   }

   foreach my $priority ( sort { $a <=> $b } keys %$transports ) {
      print '='x40 . "\n";
      &showTransports( $priority, $$transports{ $priority } );
      print '='x40 . "\n";
   }
}

sub showEntry {
   my ( $lineno, $prompt, $value ) = @_;
   $value = '' unless $value;
   return "$lineno. $prompt: $value\n";
}

sub displayEditScreen {
   my $config = shift;
   #print "\033[2J";    #clear the screen
   #print "\033[0;0H"; #jump to 0,0   
   print &showEntry( 1, 'Client Name', $config->{'clientName'} );
   print &showEntry( 2, 'Host Name', $config->{'hostname'} );
   print &showEntry( 3, 'Serial Number', $config->{'serialNumber'} );
   print &showEntry( 4, 'UUID', $config->{'UUID'} );
   print &showEntry( 5, 'Module Dirs', join( ',', $config->{'moduleDirs'} ?  @{ $config->{'moduleDirs'} } : () ) );
   print &showEntry( 6, 'Script Dirs', join( ',', $config->{'scriptDirs'} ?  @{ $config->{'scriptDirs'} } : () ) );
   print &showEntry( 7, 'Transports', '' );
   foreach my $key ( sort { $a <=> $b } keys %{ $config->{'transports'} } ) {
      print "\t$key\t" . $config->{'transports'}->{$key}->{'name'} . "\n";
   }
   print "Select Option to Edit, or 'Done' if finished [Done]: ";
   my $selection = <>;
   chomp $selection;
   $selection = 'd' unless $selection;
   return lc substr( $selection, 0, 1 );
}

sub getValue {
   my ( $prompt, $value ) = @_;
   $value = '' unless $value;
   print "$prompt [$value]: ";
   my $t = <>;
   chomp $t;
   return $t ? $t : $value;
}

sub editSelection {
   my $selection = shift;
   if ( $selection == 1 ) {
      $config->{'clientName'} = &getValue( 'Client Name', $config->{'clientName'} );
   } elsif ( $selection == 2 ) {
      $config->{'hostname'} = &getValue( 'Host Name', $config->{'hostname'} );
   } elsif ( $selection == 3 ) {
      $config->{'serialNumber'} = &getValue( 'Serial Number', $config->{'serialNumber'} );
   } elsif ( $selection == 4 ) {
      $config->{'UUID'} = &getValue( 'UUID', $config->{'UUID'} );
   } elsif ( $selection == 5 ) {
      my $t = join( ',', $config->{'moduleDirs'} ?  @{ $config->{'moduleDirs'} } : () );
      $t = &getValue( "Comma separated list of Module Directories\n\t", $t );
      my @t = split( ',', $t );
      $config->{'moduleDirs'} =  \@t;
   } elsif ( $selection == 6 ) {
      my $t = join( ',', $config->{'scriptDirs'} ?  @{ $config->{'scriptDirs'} } : () );
      $t = &getValue( "Comma separated list of Script Directories\n\t", $t );
      my @t = split( ',', $t );
      $config->{'scriptDirs'} =  \@t;
   } elsif ( $selection == 7 ) {
      print "Can not automatically do this at this time\nManually edit the file (press enter to continue)";
      my $t = <>;
   }
}

sub help {
   print "$0 version $VERSION\n";
   print "Reads one or more sysinfo configuration file and\nallows user to edit the values\n\n";
   print "$0 --verbose --file=/full/paht/to/input -output=/full/path/to/sysinfo-client.yaml\n";
   print "   --verbose may be entered more than one time to increase verbosity\n";
   print "   --file may be entered multiple times and may contain a comma delimited group of files\n";
   print "   --output is the file which will be written to\n\n";
   print "All parameters are optional\n";
   print "Will search common locations for sysinfo-client.yaml and, if found, append this to the end\n";
   print "of the input file list.\n";
   print "If no --output is passed, will write to the last --file passed or the file which was found\n";
   print "in the search\n";
   print "All parameters accept the short flag, ie -v, -f, -o and -h\n";
   exit;
}


my @confFileName;
my $outputFile;
my $verbose;
my $help;
my $version;

# handle any command line parameters that may have been passed in
# verbose is incremental, so for example, -vv would give more info than -v
# there can be multiple files passed, and an entry can have a comma
# separated list. The files will be processed in order, with the last
# one passed in being the one that overrides everything.
GetOptions (
            "verbose|v+"  => \$verbose, # verbosity level, 0-9
            'file|f=s'    => \@confFileName, # array of files to read
            'output|o=s'  => \$outputFile, # file to save to
            'help|h'      => \$help
            ) or die "Error parsing command line\n";
                  
if ( $help ) { &help() ; exit; }

# if they passed something like -f file1,file2,file3, parse it out
@confFileName = split(/,/,join(',',@confFileName));

# look for the standard configuration file in the standard place
( $confDir, $sysinfo3 ) = &findConf( $sysinfo3 );
# add it at the tail end of the list
push @confFileName, $confDir . "/" . $sysinfo3 if ( $confDir );
$outputFile = $confFileName[-1] unless $outputFile;

print "Loading defaults from existing configs\n";
$config = &makeConfig( @confFileName  );

my $selection;
while ( ( $selection = &displayEditScreen( $config ) ) ne 'd' ) {
   &editSelection( $selection );
}

if ( &yesno( "Ready to write configuration to $outputFile, ok?" ) ) {
   &writeConfig( $outputFile, &showConf( $config ) );
}

#use Data::Dumper;
#print Dumper( $config ); die;

#&doTransports( $$config{'transports'} );


1;
