1 |
#!/usr/bin/perl |
2 |
|
3 |
use strict; |
4 |
use warnings; |
5 |
|
6 |
use lib 'lib'; |
7 |
|
8 |
use Term::Shelly; |
9 |
use CWMP::Store; |
10 |
use DBM::Deep; |
11 |
use Data::Dump qw/dump/; |
12 |
use Getopt::Long; |
13 |
|
14 |
my $sh = Term::Shelly->new(); |
15 |
|
16 |
my $debug = 0; |
17 |
my $store_path = 'state.db'; |
18 |
|
19 |
GetOptions( |
20 |
'debug+' => \$debug, |
21 |
'store-path=s' => \$store_path, |
22 |
); |
23 |
|
24 |
our $store = CWMP::Store->new({ |
25 |
debug => $debug, |
26 |
path => $store_path, |
27 |
}); |
28 |
|
29 |
$sh->out( |
30 |
"You can issue commenads in form using tab-complete: |
31 |
|
32 |
CPE_Serial ( parametar [ [=] value ] | command ) |
33 |
" |
34 |
); |
35 |
|
36 |
$sh->{"completion_function"} = \&completer; |
37 |
$sh->{"readline_callback"} = \&command; |
38 |
|
39 |
my @history = ( 'exit' ); |
40 |
my $pos = $#history; |
41 |
$sh->{'mappings'}->{'up-history'} = [ sub { |
42 |
my $self = shift; |
43 |
if ( $pos >= 0 ) { |
44 |
$self->{'input_line'} = $history[ $pos ]; |
45 |
$pos--; |
46 |
$self->{'input_position'} = length( $self->{'input_line'} ); |
47 |
$self->fix_inputline; |
48 |
} |
49 |
} ]; |
50 |
$sh->{'mappings'}->{'down-history'} = [ sub { |
51 |
my $self = shift; |
52 |
my $line = ''; |
53 |
if ( $pos < $#history ) { |
54 |
$pos++; |
55 |
$line = $history[ $pos ]; |
56 |
} |
57 |
$self->{'input_line'} = $line; |
58 |
$self->{'input_position'} = length( $self->{'input_line'} ); |
59 |
$self->fix_inputline; |
60 |
} ]; |
61 |
|
62 |
my $state = 'CPE'; |
63 |
|
64 |
$sh->prompt( $state . '> ' ); |
65 |
|
66 |
while (1) { |
67 |
$sh->do_one_loop(); |
68 |
} |
69 |
|
70 |
sub completer { |
71 |
my ($line, $bword, $pos, $curword) = @_; |
72 |
|
73 |
$sh->out( "line: '$line' [ $bword - $pos ] -> '$curword'" ); |
74 |
|
75 |
my @matches; |
76 |
|
77 |
if ( $state eq 'CPE' ) { |
78 |
@matches = sort grep { /^\Q$curword\E/ } $store->known_CPE; |
79 |
$sh->out( "CPE available: ", join(",", @matches ) ); |
80 |
} |
81 |
|
82 |
return @matches; |
83 |
} |
84 |
|
85 |
sub command { |
86 |
my ( $line ) = @_; |
87 |
|
88 |
return unless ( $line && $line ne '' ); |
89 |
|
90 |
# just CPE uid |
91 |
if ( $line =~ /^(\w+)\s*$/ ) { |
92 |
if ( main->can( $1 ) ) { |
93 |
$sh->out( "# execute command $1" ); |
94 |
eval " \&$1( \$line ) "; |
95 |
} elsif ( my $state = $store->db->get('state')->get( $1 ) ) { |
96 |
$sh->out( join(" ", keys %{ $state }) ); |
97 |
push @history, $line; |
98 |
$pos = $#history; |
99 |
} else { |
100 |
$sh->out( "$line: CPE not found" ); |
101 |
} |
102 |
} else { |
103 |
$sh->out( "$line: command not recognized" ); |
104 |
} |
105 |
} |
106 |
|
107 |
sub history { |
108 |
$sh->out( "history: ", dump ( @history ) ); |
109 |
} |
110 |
|
111 |
sub exit { |
112 |
CORE::exit(); |
113 |
} |