#!/usr/bin/perl
# ************************************************************************* 
# Copyright (c) 2014, SUSE LLC
# 
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 
# 3. Neither the name of SUSE LLC nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ************************************************************************* 
#
# Dochazka CLI script
#
use 5.012;
use strict;
use warnings;

use App::CELL qw( $CELL $log $site $meta );
use App::Dochazka::CLI qw( $current_date $current_emp $current_priv $message );
use App::Dochazka::CLI::Parser;
use App::Dochazka::Model::Employee;
use Data::Dumper;
use File::ShareDir;
use Getopt::Long 2.32;
use Log::Any::Adapter;
use Pod::Usage;
use Term::ReadLine;
use Time::Piece;
use Time::Seconds;
use Try::Tiny;
use Web::MREST::CLI::UserAgent qw( send_req );
use Web::MREST::Util qw( normalize_filespec );

=head1 NAME

dochazka-cli - Command-line client for Dochazka Attendance & Time Tracking System

=head1 VERSION

Version 0.096

=cut

our $VERSION = '0.096';


=head1 SYNOPSIS

This is the Dochazka command-line interface (CLI). Options:

    --help      -h      Get help
    --user      -u      Specify username, e.g. --user=root (defaults to 'demo')
    --password  -p      Specify password (defaults to 'demo')
    --sitedir   -s      Specify sitedir (defaults to none)
    --noauth    -n      Omit authentication

The CLI enables the user to generate HTTP request (GET, PUT, POST, DELETE)
to the App::Dochazka::REST server and view the server's responses. Each
REST resource has a documented CLI syntax that can be viewed by querying
the REST server -- e.g., via a web browser.

For more information, see L<http://metacpan.org/pod/App::Dochazka::CLI>.


=head1 DESCRIPTION

This is the Dochazka command line client.


=cut

local $Data::Dumper::Terse = 1;

my $_t = localtime;
my $today = $_t->ymd;
$current_date = $today;
my $noauth = 0;

#
# logger initialization routine
#
sub init_logger {
    my $log_file = normalize_filespec( $site->DOCHAZKA_CLI_LOG_FILE );
    unlink $log_file if $site->DOCHAZKA_CLI_LOG_FILE_RESET;
    Log::Any::Adapter->set('File', $log_file );
    $log->init( ident => 'dochazka-cli', debug_mode => 1 );
    $log->debug( 'Logger initialized' );
}

#
# CLI client initialization routine: might die
#
sub init_cli_client {
    my ( $sitedir ) = @_;

    # always load the App::Dochazka::CLI distro sharedir
    my $target = File::ShareDir::dist_dir('App-Dochazka-CLI');
    print "Loading configuration files from $target\n";
    my $status = $CELL->load( sitedir => $target );
    die $status->text unless $status->ok;

    # load core config params and, if sitedir specified, site config params
    # as well
    my %CELL_ARGS = ( debug_mode => 1 );
    $CELL_ARGS{sitedir} = $sitedir if $sitedir;
    $status = $CELL->load( %CELL_ARGS );
    die $status->text unless $status->ok;

    init_logger(); 

    # initialize the LWP::UserAgent object
    Web::MREST::CLI::UserAgent::init_ua();

    return $CELL->status_ok;
}

#
# authenticate to the server
#
sub authenticate_to_server {
    my ( $user, $password ) = @_;
    print "Authenticating to server at " . $site->MREST_CLI_URI_BASE . "\n";

    # prompt for nick if none provided in site configuration
    #if ( ! $site->DOCHAZKA_REST_LOGIN_NICK ) {
    #    print "Server auth nick:     ";
    #    $meta->set( 'CURRENT_EMPLOYEE_NICK', <> );
    #}
    $meta->set( 'CURRENT_EMPLOYEE_NICK', $user );

    # prompt for password if necessary
    if ( $user ne 'demo' and $password eq 'demo' ) {
        print "Server auth password: ";
        my $input = <STDIN>;
        chomp( $input ); 
        $meta->set( 'CURRENT_EMPLOYEE_PASSWORD', $input );
        #print "Password set to " . $meta->CURRENT_EMPLOYEE_PASSWORD . "\n";
    } else {
        $meta->set( 'CURRENT_EMPLOYEE_PASSWORD', $password );
    }

    # get info about us
    my $status;
    try {
        $status = send_req( 'GET', '/employee/self/priv' );
    } catch {
        $status = $_;
    };
    if ( !ref( $status ) ) {
        print "$status\n";
        exit;
    }
    return $status unless $status->ok;
    #print Dumper( $status );
    $current_emp = App::Dochazka::Model::Employee->spawn( %{ $status->payload->{'current_emp'} } );
    $current_priv = $status->payload->{'priv'};
    return $CELL->status_ok;
}

#
# get prompt
#
sub get_prompt {
    if ( $noauth ) {
        return "App::Dochazka::CLI> ";
    } else {
        return "Dochazka($current_date) " . $current_emp->nick . " " . uc $current_priv . "> ";
    }
}


# -------------------------------------------------------------------------
# main
# -------------------------------------------------------------------------

# process command-line options
my $help = 0;
my $user = 'demo';
my $password = 'demo';
my $sitedir;
GetOptions( 
    'help|?' => \$help, 
    'user|u=s' => \$user, 
    'password|p=s' => \$password,
    'sitedir|s=s' => \$sitedir,
    'noauth|n' => \$noauth,
);
pod2usage(1) if $help;
if ( $user eq 'root' and $password eq 'demo' ) {
    # use default root password instead of demo
    $password = 'immutable';
}

# initialize CLI client
my $status;
if ( ( my $status = init_cli_client() )->not_ok ) {
    print $status->code . ' (' . $status->level . ') ' . $status->text . "\n";
    print "Response: " . Dumper( $status->payload ) . "\n";
    exit;
}

# authenticate unless --noauth given
if ( ! $noauth ) {
    if ( ( my $status = authenticate_to_server($user, $password) )->not_ok ) {

        # Handle two classic scenarios:
        # 1. server not running
        if ( $status->payload =~ m/Connection refused/ ) {
            print "Server refused connection - is it running?\n";
            exit;
        }
        # 2. authentication failed
        if ( $status->text =~ m/Authentication failed/ ) {
            print "Authentication failed.\n";
            exit;
        }

        # some other scenario?
        print $status->code . ' (' . $status->level . ') ' . $status->text . "\n";
        print "Response: " . Dumper( $status->payload ) . "\n";
        exit;
    } else {
        print "Server is alive\n";
    }
}

my $term = new Term::ReadLine 'dochazka-cli';

binmode STDOUT, ":utf8";

my $cmd;
while ( defined ( $cmd = $term->readline( get_prompt() ) ) ) {
    my @tokens = split /\s+/, $cmd;
    next unless @tokens;
    #print join( ' ', @tokens ), "\n";
    # parse_tokens will die with the status
    try { 
        App::Dochazka::CLI::Parser::parse_tokens( [], \@tokens ); 
    } catch { 
        $status = $_;
    };
    if ( ref( $status ) eq 'App::CELL::Status' ) {
        last if $status->code eq 'DOCHAZKA_CLI_EXIT';
        if ( $status->code ne 'DOCHAZKA_CLI_PARSE_ERROR' ) {
            print "HTTP status: " . ( delete $status->{'http_status'} || '<NONE>' ) . "\n";
            print "Non-suppressed headers: " . Dumper( $status->{'headers'} ) if $status->{'headers'};
            delete $status->{'headers'};
            my $expurgated_status = $status->expurgate;
            #print Dumper( $expurgated_status );
            print "Response: " . Dumper( $expurgated_status ) . "\n";
        } else {
            print( ( $status->code eq 'DOCHAZKA_CLI_PARSE_ERROR' ) 
                ? $status->text . "\n"
                : $status->code . ' (' . $status->level . ') ' . $status->text . "\n" );
        }
    } else {
        print $message, "\n";
    }
}
