#!/usr/bin/env perl

=head1 NAME

hal_client - allow me to work for hal

=cut

package HALClientCommandLine;

use FindBin qw($RealBin);
use lib "$RealBin/../lib64/perl5"; # for relative installations

BEGIN { # LIB PACK
    # API/CommandLine.pm (939f0)  API/CommandLine/Completion.pm (d182f)  Debug.pm (6ada9)  PrettyTable.pm (81c24)
    # Throw.pm (5587f)
    my %p;  open my $fh, '<', __FILE__ or die;
    /^#-+ LIB (BEGIN|END) (\S+) -+#/ && !$INC{$2} and $p{$2}{$1} = tell($fh) - ($1 eq 'END' ? length : 0) while <$fh>;
    unshift @INC, sub {
        my $beg = $p{$_[1]}->{'BEGIN'} || return;
        my $end = $p{$_[1]}->{'END'} || die "Corrupt LIB PACK on $_[1]";
        seek $fh, $beg, 0;  read $fh, my $code, $end - $beg or die;  $code =~ s/^#//mg;
        return do { open my $cfh, '<', \$code or die; $cfh };
    } if !$ENV{'SKIP_LIB_PACK'} && keys %p;
}

use strict;
use warnings;
use parent qw(API::CommandLine);

my $obj = API::CommandLine->new({dispatch_class => 'HAL::Client'});
$obj->run;

#debug $obj->run_method(hello => {foo => 'bar', test_auth => 1});
#debug $obj->run_method(revision_list => {file => 'lib/User.pm', revision => '1.527', repository => 'hosting_main'});


#----- LIB BEGIN API/CommandLine.pm -----#
#package API::CommandLine;
#
#=head1 NAME
#
#API::CommandLine - Provide an easy way to get commandline abstraction of API::Base
#
#=cut
#
#use strict;
#use warnings;
#use Throw qw(throw);
#use Scalar::Util qw(blessed);
#
#sub new {
#    my ($class, $args) = @_;
#    return bless {%{$args || {}}}, $class;
#}
#
#sub api_meta { shift->{'api_meta'} }
#sub dispatch_class { shift->{'dispatch_class'} }
#
#sub dispatch_factory { # this is identical to code in API::Server
#    my ($self, $preload) = @_;
#    return $self->{'dispatch_factory'} ||= do {
#        my $meta = $self->api_meta || $self->dispatch_class || throw "Missing one of api_meta or dispatch_class";
#        if (!ref $meta) {
#            (my $file = "$meta.pm") =~ s|::|/|g;
#            throw "Failed to load dispatch class", {class => $meta, file => $file, msg => $@} if !$meta->can('new') && !eval { require $file };
##            throw "Specified class does not have a run_method method", {class => $meta} if ! $meta->can('run_method');
#            sub { $meta->new(@_) };
#        } elsif ($meta->{'remote'}) {
#            require API::Client;
#            sub { API::Client->new({%{shift() || {}}, %$meta}) };
#        } else {
#            require API::Base;
#            API::Base->new({api_meta => $meta})->api_preload if $preload;
#            sub { API::Base->new({%{shift() || {}}, api_meta => $meta}) };
#        }
#    };
#}
#
####----------------------------------------------------------------###
#
#sub run_commandline { shift->run(@_) }
#
#sub run {
#    my ($self, $args) = @_;
#    $self = $self->new($args) if ! ref($self);
#
#    my $obj = $self->dispatch_factory->();
#    my $ARGV = $args->{'argv'} || $self->{'argv'} || \@ARGV;
#    $ARGV = [grep { /^--(json|yaml|perl|csv|show_meta)(?:=(\d))?$/ ? do { $ENV{uc $1} = $2||1; 0 } : 1 } @$ARGV];
#    return $self->completion($obj, $ARGV) if $ARGV->[0] && $ARGV->[0] eq '--shell-completion';
#
#    my $method = shift(@$ARGV) || return print $self->_pod($obj, {brief => 1});
#    return print $self->_pod($obj, {format => $1}) if $method =~ /^-{0,2}(help|h|pod|p)$/;
#    return print $self->_pod($obj, {method => $method, format => $_}) for grep {/^-{1,2}(help|h|pod|p)$/} @ARGV;
#
#    my $req;
#    if (@$ARGV == 1 && $ARGV->[0] =~ /^\{/) {
#        eval { require JSON } || throw "Single passed in arg appears to be json - but could not load JSON: $@";
#        my $json = JSON->new->utf8->allow_nonref->convert_blessed->pretty->canonical;
#        $req = eval { $json->decode($ARGV->[0]) } || throw "Could not parse json", {msg => $@, json => $json};
#    } else {
#        throw "Odd number of args passed to commandline. If you want the last value to be undef pass a :null", {argv => $ARGV, _pretty=>1} if @$ARGV % 2;
#        $req = {@$ARGV};
#        throw "Cannot use '' as a keyname - possible invalid args", {argv => $ARGV} if exists $req->{''};
#        foreach my $key (keys %$req) { $req->{$key} = __PACKAGE__->can("_$1")->() if $req->{$key} && $req->{$key} =~ /^:(null|true|false)$/ }
#        my $has_uriencode = !$self->{'no_data_uriencode'} && eval { require Data::URIEncode };
#        warn "WARNING: You do not have Data::URIEncode installed but appear to be expecting its behavior!\n" if ! $self->{'no_data_uriencode'} && ! $has_uriencode && grep { /\w+[:.]./ } keys %$req;
#        $req = Data::URIEncode::flat_to_complex($req) || {} if $has_uriencode;
#    }
#
#    my $data = $self->_run_method($obj, $method, $req);
#    my $meta = $ENV{'SHOW_META'} ? $self->_run_method($obj,"${method}__meta", $req) : undef;
#    $self->print_data($data, $req, $meta);
#    exit(1) if ref($data) && eval { $data->{'error'} };
#}
#
#sub run_method {
#    my ($self, $method, $args) = @_;
#    $self = $self->new($args) if ! ref($self);
#    my $obj = $self->dispatch_factory->();
#    return $self->_run_method($obj, $method, $args);
#}
#
#sub _remote_ip { shift->{'remote_ip'} || $ENV{'REMOTE_ADDR'} || (($ENV{'REALUSER'} || $ENV{'SUDO_USER'}) ? 'sudo' : 'cmdline') };
#
#sub _remote_user { shift->{'remote_user'} || $ENV{'REALUSER'} || $ENV{'SUDO_USER'} || $ENV{'REMOTE_USER'} || $ENV{'USER'} || (getpwuid($<))[0] || '-unknown-' }
#
#sub _brand { shift->{'brand'} || $ENV{'BRAND'} || $ENV{'PROV'} if $ENV{'BRAND'} || $ENV{'PROV'} }
#
#sub _caller { ['commandline'] }
#
#sub _script {
#    my $self = shift;
#    my $s = $self->{'script'} || $ENV{'SCRIPT_NAME'} || $0;
#    $s =~ s|.+/|| if ! $self->{'full_script'};
#    return $s;
#}
#
#sub _token {
#    my ($self, $args) = @_;
#    return $args->{'_t'} || $self->{'token'} || $ENV{'ADMIN_API_TOKEN'};
#}
#
#sub _run_method {
#    my ($self, $obj, $method, $args, $extra) = @_;
#
#    local $args->{'_c'} = $self->_caller if ! $self->{'no_trace'};
#    local $obj->{'transport'}   = $self->{'transport'} || 'cmdline';
#    local $obj->{'remote_user'} = $self->_remote_user($args);
#    local $obj->{'remote_ip'}   = $self->_remote_ip($args);
#    local $obj->{'api_ip'}      = $obj->{'remote_ip'};
#    local $obj->{'api_brand'}   = $self->_brand($args);;
#    local $obj->{'return_raw'} = 1 if $ENV{'RAW'};
#    #local $obj->{'script'}      = $self->_script($args);
#    my $t = $self->_token($args);
#    local $obj->{'token'} = $t if $t;
#    $obj->commandline_init($method, $args, $self) if $obj->can('commandline_init');
#
#    my $run = sub {
#        my $data = eval { $obj->can('run_method') ? $obj->run_method(@_) : $obj->$method($args, ($extra ? $extra : ())) };
#        $data = $@ if ! ref $data;
#        return !ref($data) ? {error => 'Commandline failed', msg => $data} : (blessed($data) && $data->can('data')) ? $data->data : $data;
#    };
#    my $ref = $run->($method, $args, $extra);
#    while (ref($ref) ne 'ARRAY' && $ref->{'error'}) {
#        last if !$ref->{'type'} || $ref->{'type'} !~ /^token_\w+$/;
#        last if $self->{'no_token_retry'};
#        warn "Prompting for authorization and retry ($ref->{'type'}: $ref->{'error'})\n";
#        eval { require IO::Prompt } || throw "Please install IO::Prompt to authenticate from commandline", {msg => $@};
#        my $user = ''.IO::Prompt::prompt("  Web Auth Username: ", -d => $obj->{'remote_user'}) || $obj->{'remote_user'};
#        my $pass = ''.IO::Prompt::prompt("  Web Auth Password ($user): ", -e => '*') || throw "Cannot proceed without password";
#        my $key  = ($obj->can('config') && $obj->config('plaintext_public_key'))
#            || ($obj->can('_configs') && $obj->_configs->{'plaintext_public_key'})
#            || $config::config{'plaintext_public_key'};
#        if (!$key) {
#            warn "  Could not find plaintext_public_key in config - sending plaintext password\n";
#        } elsif (!eval { require Crypt::OpenSSL::RSA }) {
#            warn "  (Crypt::OpenSSL::RSA is not installed - install to avoid sending plaintext password)\n";
#        } else {
#            my $c = Crypt::OpenSSL::RSA->new_public_key($key);
#            my $len = length($pass) + 1;
#            $pass = pack 'u*', $c->encrypt(pack "Z$len", $pass);
#            $pass = "RSA".length($pass).":$pass";
#        }
#        $obj->{'token'} = "$user/i:cmdline/$pass";
#        $ref = $run->(hello => {test_auth => 1});
#        $self->{'token'} = $obj->{'token'} = $ref->{'token'} || throw "Did not get a token back from successful test_auth", {data => $ref};
#        warn "\nexport ADMIN_API_TOKEN=$obj->{'token'}\n\n";
#        $ref = $run->($method, $args, $extra);
#    }
#    return $ref;
#}
#
#sub print_data {
#    my ($self, $data, $args, $meta) = @_;
#    if (ref($data) eq 'ARRAY' && @$data == 3) {
#        eval { require API::Server } || throw "Could not load API::Server to display psgi response", {msg => $@, data => $data};
#        my $s = API::Server->new({'API::CommandLine' => 1, non_daemon => 1});
#        $s->send_psgi_response($data);
#        exit;
#    }
#    if ($ENV{'CSV'}) {
#        my @fields = grep {ref($data->{$_}) eq 'ARRAY' && ref($data->{$_}->[0]) eq 'HASH'} sort keys %$data;
#        @fields = ('rows') if ! @fields && ref($data->{'rows'}) eq 'ARRAY' && ! @{$data->{'rows'}};
#        require Text::CSV_XS;
#        my $csv = Text::CSV_XS->new({eol => "\n"});
#        foreach my $field (@fields) {
#            print "----- $field -------------------------\n" if @fields > 1;
#            my @keys = sort {($a eq 'id') ? -1 : ($b eq 'id') ? 1 : $a cmp $b } keys %{ $data->{$field}->[0] || {'-no-rows-'=>1} };
#            $csv->print(\*STDOUT, \@keys) if $ENV{'CSV'} ne '2';
#            $csv->print(\*STDOUT, [map {ref($_) eq 'ARRAY' ? join(",",@$_) : ref($_) eq 'HASH' ? join(",",%$_) : $_} @$_{@keys}]) for @{ $data->{$field} };
#        }
#        exit;
#    }
#    if ($ENV{'YAML'}) {
#        eval { require YAML } || throw "Could not load YAML for output", {msg => $@};
#        print YAML->new->Dump($data);
#    } elsif ($ENV{'JSON'} || ! eval { require PrettyTable }) {
#        eval { require JSON } || throw "Could not load JSON for output", {msg => $@};
#        my $json = JSON->new->utf8->allow_nonref->convert_blessed->pretty->canonical;
#
#        my $out = $json->encode($data);
#        if ($ENV{'JSON'} eq '2') {
#            $out = ($ENV{'SHOW_META'} ? "meta = ".$json->encode($meta)."\n" : '')
#                . "args = ".$json->encode($args)."\ndata = $out\n";
#        }
#        utf8::decode($out);
#        print $out;
#
#    } elsif ($ENV{'PERL'}) {
#        if ($ENV{'PERL'} == 2) {
#            if (eval { require Debug }) {
#                Debug::debug($meta, $args, $data);
#            } else {
#                require Data::Dumper;
#                print Data::Dumper::Dumper($_) for $ENV{'SHOW_META'} ? $meta : (), $args, $data;
#            }
#        } else {
#            require Data::Dumper;
#            local $Data::Dumper::Terse = 1;
#            print Data::Dumper::Dumper($data);
#        }
#    } elsif ($ENV{'RAW'} && $ENV{'RAW'} == 2) {
#        print $data->{'content'};
#        print "\n" if -t STDIN && $data->{'content'} !~ /\n\z/;
#    } else {
#        if ($ENV{'SHOW_META'}) {
#            print "Meta:\n";
#            print PrettyTable->plain_text($meta, {auto_collapse => 1});
#        }
#        print "Arguments:\n";
#        print PrettyTable->plain_text($args, {auto_collapse => 1});
#        if ((scalar(keys %$data) == 1 || $data->{'n_pages'} && $data->{'n_pages'} =~ /^(?:1|not calculated)$/) && $data->{'rows'}) {
#            print "Data Rows:\n";
#            print PrettyTable->plain_text($data->{'rows'}, {auto_collapse => 1});
#        } else {
#            print "Data:\n";
#            print PrettyTable->plain_text($data, {auto_collapse => 1});
#        }
#    }
#}
#
#sub _false { require JSON; JSON::false() }
#sub _null  { undef }
#sub _true  { require JSON; JSON::true() }
#
#sub _pod {
#    my ($self, $obj, $args) = @_;
#    my $class = ref($obj);
#    my $script = $args->{'script'} || $0;
#    my $meth   = $args->{'method'} || 'methodname';
#    my $out = "=head1 NAME\n\n"
#        ."$script - commandline interface to $class methods\n\n"
#        ."=head1 SYNOPSIS\n\n"
#        ."    $script $meth\n\n"
#        ."    $script $meth --help\n\n"
#        ."    $script $meth methods   # brief list of methods \n\n"
#        ."    $script $meth key1 value1 key2 value2\n\n"
#        ."    $script $meth key1:0 arrayvalue1 key1:1 arrayvalue2\n\n"
#        ."    JSON=1 $script $meth key1 value1 key2 value2 (Produces only valid JSON.)\n\n"
#        ."    JSON=2 $script $meth key1 value1 key2 value2 (Produces JSON decorated with field descriptions.)\n\n"
#        ."    YAML=1 $script $meth key1 value1 key2 value2\n\n"
#        ."    PERL=1 $script $meth key1 value1 key2 value2 (Produces only valid Perl structure.)\n\n"
#        ."    PERL=2 $script $meth key1 value1 key2 value2 (Produces Perl decorated with '\$VAR1 = '.)\n\n"
#        ."    CSV=1 $script $meth key1 value1 key2 value2 (only works for fields that are arrays of hashes)\n\n"
#        ."    CSV=2 $script $meth key1 value1 key2 value2 (same as =1, but omits the field header)\n\n"
#        ."    RAW=1 $script $meth key1 value1 (if running on API::Client will a hashref containing status, headers, content)\n\n"
#        ."    RAW=2 $script $meth key1 value1 (if running on API::Client will print the raw response)\n\n"
#        ."    SHOW_META=1 $script $meth key1 value1 key2 value2 (includes meta information for $meth)\n\n"
#        ."Arguments for the hashref should be passed on the commandline as"
#        ." simple key value pairs.  If the arguments are more complex, you can"
#        ." pass values in any of the ways that L<Data::URIEncode> supports.\n\n"
#        ."=head1 METHODS\n\n";
#    if ($args->{'brief'}) {
#        $out .= join(", ", sort keys %{ $self->_run_method($obj, methods => {})->{'methods'} })."\n\n";
#    } else {
#        my $methods;
#        if ($meth ne 'methodname') {
#            my $meta = $self->_run_method($obj, "${meth}__meta", {_flat => 1});
#            if (my $rest = $meta->{'rest'}) {
#                my $fmt = $obj->can('uri_as_str') || sub { my ($obj, $uri) = @_; ref($uri) eq 'ARRAY' ? "@$uri" : "$uri" };
#                my @rest = map { uc($_->[0] || 'ANY')." ".$fmt->($obj, $_->[1])} ref($rest->[0]) ? @$rest : $rest;
#                $meta = {%$meta, rest => \@rest};
#            }
#            $methods = {$meth => $meta};
#        } else {
#            $methods = $self->_run_method($obj, methods => {meta => 1, _flat => 1})->{'methods'};
#        }
#        foreach my $meth (sort keys %$methods) {
#            my $m = $methods->{$meth};
#            $out .= "=head2 C<$meth>\n\n";
#            $out .= "    $_\n" for @{ $m->{'rest'} };
#            $out .= "$m->{'desc'}\n\n" if $m->{'desc'};
#            $out .= "=over 4\n\n";
#            my $args = $m->{'args'}; my %uk;
#            foreach my $field (grep {!$uk{$_}++} (map {split /\s*,\s*/} ref($args->{'group order'}) ? @{$args->{'group order'}} : $args->{'group order'}||()), grep {!/^group /} sort keys %$args) {
#                $out .= "=item C<$field>\n\n";
#                Debug::debug($meth, $field, $args->{$field}) if ! ref($args->{$field}) && eval {require Debug};
#                $out .= "(required)\n\n" if $args->{$field}->{'required'};
#                $out .= "$args->{$field}->{'desc'}\n\n" if $args->{$field}->{'desc'};
#            }
#            $out .= "=back\n\n";
#        }
#    }
#    $out .= "=cut\n";
#    if (!$args->{'format'} || ($args->{'format'} && $args->{'format'} =~ /h/)) {
#        require Pod::Text;
#        my $cols = $ENV{'COLUMNS'} || eval { die if ! -t STDOUT; require Term::ReadKey; (Term::ReadKey::GetTerminalSize(\*STDOUT))[0] } || 80;
#        my $txt = '';
#        open my $fh_out, '<', \$out or throw "Could not open scalar out: $!";
#        open my $fh_in, '>', \$txt or throw "Could not open scalar in: $!";
#        Pod::Text->new(width => $cols)->parse_from_file($fh_out, $fh_in);
#        return $txt;
#    }
#    return $out;
#}
#
#sub completion {
#    my ($self, $obj, $argv) = @_;
#    my $pkg = $self->completion_class($obj);
#    (my $file = "$pkg.pm") =~ s|::|/|g;
#    require $file if ! $pkg->can('complete');
#    $pkg->complete($self, $obj, $argv);
#}
#
#sub completion_class {
#    my ($self, $obj) = @_;
#    my $meth = 'completion_class';
#    return $self->{$meth} || ($obj->can($meth) && $obj->$meth()) || 'API::CommandLine::Completion';
#}
#
#1;
#----- LIB END API/CommandLine.pm -----#

#----- LIB BEGIN Throw.pm -----#
#package Throw;
#
#=head1 NAME
#
#Throw - Simple exceptions that do the right things in multiple contexts
#
#=cut
#
#use strict;
#use warnings;
#use overload '""' => \&_str, fallback => 1;
#
#our ($base_level, $level, $max_args, $max_arg_len, @EXPORT, $trace, $pretty, $js, $jp, %skip) = (0, 0, 5, 20, 'throw');
#
#sub import {
#    no strict 'refs'; my ($me, $you, $f, $l) = (shift, caller(@_ && defined($_[0]) && $_[0] =~ /^\d+$/ ? shift() : 0));
#    for my $sub (@_ ? @_ : @{"$me\::EXPORT"}) {
#        die "Cannot export $sub from $me to $you at $f line $l.\n" if ! defined &{"$me\::$sub"};
#        die "Sub $sub is not in ${me}::EXPORT_OK at $f line $l.\n" if @{"$me\::EXPORT_OK"} && !grep {$sub eq $_} @{"$me\::EXPORT_OK"};
#        *{"$you\::$sub"} = \&{"$me\::$sub"};
#    }
#}
#*export_to_level = \&import;
#
#sub throw   { local $base_level = 1; die __PACKAGE__->new(@_) }
#sub croak   { local ($base_level, $trace) = (2, 1);  die __PACKAGE__->new(@_) } # die from perspective of caller
#sub carp    { local ($base_level, $trace) = (2, 1); warn __PACKAGE__->new(@_) } # warn from caller
#sub confess { local ($base_level, $trace) = (1, 2);  die __PACKAGE__->new(@_) } # die with full trace
#sub cluck   { local ($base_level, $trace) = (1, 2); warn __PACKAGE__->new(@_) } # warn with trace
#
#sub new {
#    my ($class, $e, $i, $l) = @_;
#    if (! ref $e) {
#        my %e = %{$i || {}};
#        $e{'_error'} = $e{'error'} if exists $e{'error'};
#        $e{'error'} = $e;
#        $e = \%e;
#    }
#    $e->{'trace'} = caller_trace($trace || $e->{'trace'}, $l) if $trace || $e->{'trace'};
#    return bless $e, $class;
#}
#
#sub _str {
#    my $self = shift;
#    my $err  = $self->{'error'} || "Something happened";
#    my $p    = defined($pretty) ? $pretty : $self->{'_pretty'};
#    local @$self{'error','_pretty'};  delete @$self{'error','_pretty'};
#    return "$err\n" if !scalar keys %$self;
#    require JSON;
#    my $j = $p ? $jp ||= JSON->new->allow_unknown->allow_blessed->utf8->convert_blessed->canonical->pretty
#               : $js ||= JSON->new->allow_unknown->allow_blessed->utf8->convert_blessed->canonical;
#    return "$err: ".$j->encode({%$self}).($p ? '' : "\n");
#}
#
#sub caller_trace {
#    my ($verbose, $lev) = @_;
#    return $verbose if $verbose !~ /^[123]$/;
#    my $i = ($lev || $level) + $base_level + 1;
#    return sprintf "Called from %s at %s line %s", (caller $i+1)[3]||'main', map{s|^(?:.+/)?lib/||;$_} (caller $i)[1,2] if $verbose && $verbose eq '1';
#    my ($m1, $m2, $m3, $lpkg, $nv, @trace) = (0, 0, 0, __PACKAGE__, eval {require 5.014} ? $verbose ne '3' : 1);
#    while (1) {
#        my ($pkg, $file, $line, $sub, $args) = $nv ? ((caller $i++)[0..3], [])
#            : do { package DB; local $DB::args[0] = \$nv; ((caller $i++)[0..3], ($DB::args[0]||'') ne \$nv ? [@DB::args] : []) };
#        last if ! $sub;
#        $args = [] if $lpkg eq __PACKAGE__;
#        $lpkg = $pkg;
#        $sub =~ s/.*://; $file =~ s|^(?:.+/)?lib/||;
#        next if ($file eq __FILE__) || $skip{$file} || $skip{$pkg} || $skip{$sub};
#        splice @$args, $max_args, -1, '...' if @$args > $max_args;
#        $args = !@$args ? '' : ' ('.join(', ',map{$_=!defined($_)?'undef':ref($_)||!/\D/?$_:do{(my$c=$_)=~s|([\'/])|\\$1|g;"'$c'"}; substr($_,0,$max_arg_len)} @$args).')';
#        $m1 = length $sub  if length($sub)  > $m1;
#        $m2 = length $file if length($file) > $m2;
#        $m3 = length $line if length($line) > $m3;
#        push @trace, [$sub, $file, $line, $args];
#    }
#    return join "\n", map {sprintf "%-${m1}s at %-${m2}s line %${m3}s%s", @$_} @trace;
#}
#
#sub TO_JSON { return {%{$_[0]}} }
#
#sub classify {
#    my ($err, $ref) = @_;
#    $ref = {$ref => 1} if ! ref $ref;
#    my $type = !ref($err) ? 'undef.flat' : defined($err->{'type'}) ? $err->{'type'} : 'undef.none';
#    my @keys = grep {$_ ne 'default'} keys %$ref;
#    @keys = sort {length($b) <=> length($a) || $a cmp $b} @keys if @keys > 1;
#    foreach my $key (@keys) {
#        next if $type !~ /^\Q$key\E\b(?:$|\.)/;
#        my $val = $ref->{$key};
#        return ref($val) ? $val->($err, $key) : $val;
#    }
#    return if ! exists $ref->{'default'};
#    my $val = $ref->{'default'};
#    return ref($val) ? $val->($err, 'default') : $val;
#}
#
#1;
#----- LIB END Throw.pm -----#

#----- LIB BEGIN PrettyTable.pm -----#
#package PrettyTable;
#
#=head1 NAME
#
#PrettyTable - Allow for auto-fixed-widith formatting of raw data
#
#=cut
#
#use strict;
#use warnings;
#
#our @border = ('| ', ' | ', ' |', ' ',
#               '+-', '-+-', '-+', '-',
#               '+-', '-+-', '-+', '-',
#               '+-', '-+-', '-+', '-');
#our @borderu = ("│ ", " │ ", " │", ' ',
#                '┌─', '─┬─', '─┐', '─',
#                '├─', '─┼─', '─┤', '─',
#                '└─', '─┴─', '─┘', '─');
#our $unibox = 1;
#our $split  = 100;
#our $qr_escape = "[^ -~]";
#our @EXPORT = qw(pretty_table);
#
#sub import {
#    no strict 'refs';  my $cl = shift;  my $pkg = caller;  @_ = @{"${cl}::EXPORT"} if ! @_;
#    !/^(?:_|new)/ && defined &{"${cl}::${_}"} ? (*{"${pkg}::${_}"} = \&{"${cl}::${_}"}) : die "Cannot export $_ from $cl to $pkg.\n" for @_;
#}
#
#sub new {
#    my $class = shift;
#    return bless ref($_[0]) ? $_[0] : {@_}, $class;
#}
#
#sub pretty_table { __PACKAGE__->_tablify(@_) }
#sub plain_text { shift->_tablify(@_) }
#
#sub _tablify {
#    my ($self, $data, $args) = @_;
#    $self = $self->new($args || {}) if ! ref $self;
#    local $self->{'_level'} = 1 + ($self->{'_level'} || 0);
#
#    my $uni   = exists($self->{'unibox'}) ? $self->{'unibox'} : $unibox;
#    local $split = $self->{'split'} || $split if $self->{'_level'} == 1;
#    local @border = ref($uni) ? @$uni : map {utf8::decode(my $c = $_); $c} @borderu
#        and !$uni or local $qr_escape = "[^ -~".join('', @border)."]" if $uni && $self->{'_level'} == 1;
#
#    my @bucket;
#    my @title;
#    my @max;
#    my @dir;
#    my $add = sub {
#        my ($cols, $bucket) = @_;
#        if (!ref($cols)) {
#            for my $chunk ($split ? map {/(.{$split}|.+)/g} split /\n/, $cols : split /\n/, $cols) {
#                push @$bucket, $chunk;
#            }
#            return;
#        }
#        my $i = @$bucket;
#        for my $j (0 .. $#$cols) {
#            my $_split = $split;
#            my $val = $cols->[$j];
#            if (! defined $val) {
#                $val = '(undef)';
#            } elsif (ref $val) {
#                if (UNIVERSAL::isa($val, 'SCALAR')) {
#                    $val = (defined(&JSON::true)  && JSON::true()  eq $val) ? '(true)'
#                         : (defined(&JSON::false) && JSON::false() eq $val) ? '(false)'
#                         : "\\\"$$val\"";
#                } elsif (ref($val) eq 'CODE') {
#                    $val = '(coderef)';
#                } else {
#                    chomp($val = $self->_tablify($val));
#                    $_split = 0 if $_split && $val =~ /^\Q$border[4]\E/ && $val =~ /\Q$border[14]\E$/;
#                }
#            }
#            $dir[$j] = 1 if $val =~ /\D/ && $bucket == \@bucket; # TODO - we could work on our alignment
#            my $I = $i;
#            for my $chunk ($_split ? map {/(.{$_split}|.+)/g} split /\n/, $val : split /\n/, $val) {
#                $chunk =~ s/($qr_escape)/sprintf "\\%03o", ord $1/eg;
#                $bucket->[$I++]->[$j] = $chunk;
#                $max[$j] = length($chunk) if !$max[$j] || $max[$j] < length($chunk);
#            }
#        }
#    };
#
#
#    if (UNIVERSAL::isa($data, 'HASH')) {
#        my $title = $self->{'title'};
#        $add->($title, \@title) if $title;
#        my @keys = @{ $self->{'sort'} || [sort {($a eq 'id') ? -1 : ($b eq 'id') ? 1 : $a cmp $b } keys %$data] };
#        $add->([$_, $data->{$_}], \@bucket) for @keys;
#        $add->(['(empty hash)'], \@bucket) if !@bucket;
#    } elsif (UNIVERSAL::isa($data, 'ARRAY')) {
#        my %title;
#        if ($data->[0] && ref($data->[0]) eq 'HASH' && !$self->{'collapse'}) {
#            @title{keys %$_} = () for grep {ref($_) eq 'HASH'} @$data; # find all uniques
#            my @keys = @{ $self->{'sort'} || [sort {($a eq 'id') ? -1 : ($b eq 'id') ? 1 : $a cmp $b } keys %title] };
#            $add->(\@keys, \@title);
#            foreach my $row (@$data) {
#                if (ref($row) ne 'HASH') {
#                    $add->($row, \@bucket);
#                    next;
#                }
#                $add->([@$row{@keys}], \@bucket);
#            }
#        } else {
#            my $title = $self->{'title'};
#            $add->($title, \@title) if $title;
#            $add->([$_], \@bucket) for @$data;
#            $add->(['(empty array)'], \@bucket) if !@bucket;
#        }
#    }
#
#    my $indent = $self->{'indent'} || '';
#    my $sep = "${indent}$border[8]".join($border[9], map {$border[11] x $_} @max)."$border[10]\n";
#    my $fmt = "${indent}$border[0]".join($border[1], map {'%'.($dir[$_] ? '-' : '').$max[$_].'s'} 0..$#max)."$border[2]\n";
#
#    if (!$self->{'collapse'} and my $cols = $self->{'auto_collapse'}) {
#        $cols = $ENV{'COLUMNS'} || eval { die if ! -t STDOUT; require Term::ReadKey; (Term::ReadKey::GetTerminalSize(\*STDOUT))[0] } || 80 if $cols eq '1';
#        if (length($sep) - 1 > $cols) {
#            local $self->{'collapse'} = 1;
#            local $self->{'_level'} if $self->{'_level'} == 1;
#            return $self->_tablify($data);
#        }
#    }
#
#    my $out = "";
#    $out .= "${indent}$border[4]".join($border[5], map {$border[7] x $_} @max)."$border[6]\n";
#    no warnings 'uninitialized'; # because of multiline
#    for my $buck (\@title, \@bucket) {
#        for my $row (@$buck) {
#            if (ref $row) {
#                $out .= sprintf $fmt, @$row[0..$#max]; # force to full width to avoid sprint warn
#            } else {
#                $out .= sprintf("$border[0]%-*s$border[2]\n", length($sep) - (length($border[0])+length($border[2])+1), $row);
#            }
#        }
#        if ($buck == \@title) {
#            $out .= $sep if @title;
#        } else {
#            $out .= "${indent}$border[12]".join($border[13], map {$border[15] x $_} @max)."$border[14]\n";
#        }
#    }
#
#    utf8::encode($out) if $self->{'_level'} == 1;
#    return $out;
#}
#
#1;
#----- LIB END PrettyTable.pm -----#

#----- LIB BEGIN API/CommandLine/Completion.pm -----#
#package API::CommandLine::Completion;
#
## API::CommandLine::Completion - Provide support for completion in API::CommandLine
## see pod for more details
#
#use strict;
#use warnings;
#use Debug;
#use Throw qw(throw);
#
#our $MAX_VALUE_MATCHES = 200;
#our $CACHE_MINUTES = 60;
#our $NO_SQL_COMPLETION_FUNCTIONS;
#
#sub run_method {
#    my $self = shift;
#    return $self->cmdline->_run_method($self->object, @_);
#}
#
#sub cmdline { shift->{'cmdline'} || throw "Missing cmdline handoff", {trace => 2} }
#sub object  { shift->{'object'}  || throw "Missing object handoff", {trace => 2} }
#sub program { shift->{'program'} || throw "Missing program" }
#
#sub new { bless {}, shift() || __PACKAGE__ }
#
#sub complete {
#    my ($self, $cmdline, $obj, $argv) = @_;
#    $self = $self->new;
#
#    my $ind = shift @$argv // '';
#    $ind = shift @$argv || return if $ind eq '--shell-completion';
#    my $prog = $argv->[0] || 'unknown';
#    $prog =~ s|.*/||;
#    $prog =~ y|a-z0-9_-||cd;
#
#    local $self->{'program'} = $prog;
#    local $self->{'cmdline'} = $cmdline;
#    local $self->{'object'}  = $obj;
#
#    local $obj->{'transport'} = 'cmdline-completion';
#    local $SIG{'__WARN__'} = sub { } if ! $ENV{'NO_HIDDEN_COMPLETION_WARN'};
#
#    my $cur = $argv->[$ind] // '';
#    my $meth = $argv->[1];
#    $cur =~ s/\\([^\w\.,!=+@*:-])/$1/g if $cur;
#    local $self->{'cur'} = \$cur;
#
#    # valid method names
#    my @res;
#    if ($ind == 1) {
#        @res = $self->methods_list($meth // '');
#
#    # value options
#    } elsif ($ind % 2) {
#        my $arg = $argv->[$ind - 1];
#        @res = $self->arg_values($meth, $arg, $cur, $ind, $argv);
#
#    # argument names
#    } else {
#        @res = $self->method_args($meth, $cur, $ind, $argv);
#
#    }
#
#    $self->print_out($_) for grep { !defined($cur) || /^\Q$cur\E/i } @res;
#    return;
#}
#
#sub print_out {
#    my ($self, $item) = @_;
#    $item =~ s/([^\w\.,!=+@*:-])/\\$1/g;
#    $item =~ s/^([^\w\.!=+@-])/\\$1/;
#    print "$item\n";
#}
#
#sub methods_list {
#    my ($self, $meth) = @_;
#    return $meth if $meth =~ s/__[meta]*$/__meta/;
#    my $methods = $self->get_or_set(methods => sub { $self->run_method(methods => {}) }, 1)->{'methods'};
#    return sort keys %$methods;
#}
#
#sub method_args {
#    my ($self, $meth, $cur, $ind, $argv) = @_;
#    my $meta = eval { $self->method_meta($meth) } || return;
#    my $args = $meta->{'args'} || return;
#    my @res;
#    foreach my $arg (sort keys %$args) {
#        next if $arg =~ /^group /;
#        my $ref = $args->{$arg};
#        $ref = {} if ! ref $ref;
#        next if $arg =~ /^_/ && ! grep {$_ !~ /^(?:min_in_set|max_in_set|name|delegate_error|order)$/} keys %$ref; # skip min_in_set fields that delegate to other fields
#        push @res, $arg;
#        push @res, $ref->{'alias'} if $ref->{'alias'};
#    }
#    return @res;
#}
#
#sub method_meta {
#    my ($self, $meth) = @_;
#    return $self->get_or_set("${meth}__meta" => sub { $self->run_method("${meth}__meta", {_flat => 1}) }, 1);
#}
#
#sub arg_values {
#    my ($self, $_meth, $arg, $cur, $ind, $argv) = @_;
#    return if ! defined $arg;
#    my $e = $self->value_completion_meta($_meth, $arg);
#    if (!$e) {
#        return $self->arg_values_gs_select($_meth, lc($arg), $cur, $ind, $argv) if $arg =~ /^(?:select|group_by|order_by)$/i;
#        return;
#    }
#    my $key = $e->{'cache_name'} || return;
#    my $values = $self->get_or_set($key => sub {
#        my $meth  = $e->{'m'} || $_meth;
#        my $field = $e->{'f'} || $e->{'id'} || $arg;
#        my $key   = $e->{'k'} || 'rows';
#        my %margs = %{ $e->{'args'} || {} };
#        $self->augment_arg_value_query(\%margs, $field, $cur, $e->{'type'}, $e) if $field && length($cur) && !$e->{'cacheable'};
#        my $sel = $e->{'distinct'} ? "DISTINCT($field) AS $field" : $field;
#        my $rows = eval {
#            my $data = $self->run_method($meth => {select => $sel, order_by => $field, %margs, _flat => 1, limit => $MAX_VALUE_MATCHES});
#            return $data->{$key} || throw "Could not find $key in return data", {data => $data};
#        };
#        if (! $rows) {
#            print STDERR "Failed to lookup completions: $@\n";
#            return {options => []};
#        }
#        my %seen;
#        for my $row (@$rows) {
#            my $val = ref($row) ? $row->{$field} : $row;
#            $seen{$val}++;
#        }
#        @seen{qw(NULL NOTNULL)} = (1,1) if $e->{'nullable'};
#        $seen{"(zz-more-than-$MAX_VALUE_MATCHES-matches)"}++ if @$rows >= $MAX_VALUE_MATCHES;
#        return {options => [sort keys %seen], ($e->{'cacheable'} ? (cacheable => 1) : ())};
#    }, 0)->{'options'};
#    return @$values;
#}
#
#sub value_completion_meta {
#    my ($self, $meth, $arg) = @_;
#    my $meta = eval { $self->method_meta($meth) } || {};
#    my $args = $meta->{'args'} || {};
#    my $ameta = ref($args->{$arg}) ? $args->{$arg} : {};
#    my $e = $ameta->{'completion'};
#    if ($e) {
#        $e->{'cache_name'} = "$meth--$arg";
#    } else {
#        if ($e = $ameta->{'api_enum'}) {
#            $e->{'cacheable'} = 1;
#            $e->{'cache_name'} = "$meth--$arg";
#        } else {
#            my $all = $self->get_or_set('methods--general_arg_completions' => sub {
#                return {completions => $self->run_method(methods => {completions => 1, _flat => 1})->{'completions'} || {}};
#            }, 1)->{'completions'};
#            if ($all->{$meth}) {
#                if ($e = $all->{$meth}->{$arg}) {
#                    $e->{'cache_name'} = "$meth--$arg";
#                } elsif (ref($args->{$arg}) && ! $args->{$arg}->{'option'} and $e = $all->{$meth}->{'*'}) {
#                    $e = {m => $meth, %$e, cache_name => "$meth--$arg", f => $arg};
#                }
#            }
#            if (!$e and my $qrm = (sort {length($b) <=> length($a)} grep { $_ =~ /[^\w\.\-]+/ && $meth =~ /^$_$/ } keys %$all)[0]) {
#                if ($e = $all->{$qrm}->{$arg}) {
#                    $e->{'cache_name'} = "$qrm--$arg";
#                } elsif (ref($args->{$arg}) && ! $args->{$arg}->{'option'} and $e = $all->{$qrm}->{'*'}) {
#                    $e = {m => $meth, %$e, cache_name => "$qrm--$arg", f => $arg};
#                }
#            }
#            if (!$e and $e = $all->{$arg}) {
#                $e->{'cache_name'} = "global--arg--$arg";
#            }
#        }
#    }
#    $e->{'type'} ||= $ameta->{'type'} if $ameta->{'type'};
#    return $e;
#}
#
#sub augment_arg_value_query {
#    my ($self, $args, $field, $cur, $type) = @_;
#    if ($type && $type eq 'ip') {
#        my $low = my $high = $cur;
#        $_ = [split /\./, $_] for $low, $high;
#        for my $i ($high->[-1]) { last if ! $i; $i .= 9 for length($i)..2; $i > 300 ? chop($i) : ($i = 255) if $i > 255 }
#        push @$low,    0 for $#$low+1  .. 3;
#        push @$high, 255 for $#$high+1 .. 3;
#        $_ = join '.', @$_ for $low, $high;
#        $args->{'where'} = [$field => {'>=', $low}, $field => {'<=', $high}];
#    } else {
#        $args->{$field} = {like => "$cur%"};
#    }
#}
#
#sub arg_values_gs_select {
#    my ($self, $meth, $arg, $cur, $ind, $argv) = @_;
#    my $meta = eval { $self->method_meta($meth) } || return;
#    my $args = $meta->{'args'} || return;
#    return if ! $args->{$arg} || ! $args->{$arg}->{'option'};
#    my @val = sort grep {!ref($args->{$_}) || !$args->{$_}->{'option'}} grep {!/^group /} keys %$args;
#    my @func = qw{NULL * COUNT(*) DISTINCT( NOW() UTC_TIMESTAMP() DATE_ADD( DATE_SUB( CONVERT_TZ(};
#    push @val, @func if ! $NO_SQL_COMPLETION_FUNCTIONS && $arg eq 'select';
#    return @val if ! defined($cur) || $cur =~ /^\s*$/;
#    my $qr = join '|', map {"\Q$_\E"} sort {length($b) <=> length($a)} @val;
#    if ($cur =~ s/(["'\)])\s*$/$1,/ || $cur =~ s/\(\s*$/(/
#        || ($cur =~ /\b($qr)[,\s]*$/i && (1 == grep { $_ =~ /^\Q$1\E/i } @val) &&  $cur =~ s/\b($qr)[,\s]*$/$1,/i)) {
#        ${ $self->{'cur'} } = undef;
#        return map {"$cur$_"} @val;
#    } elsif ($cur =~ s/\s*([\(,])\s*(\w+(?:|\(\*?\)|\())\s*$/$1/) {
#        my $last = $2;
#        @val = grep { $_ =~ /^\Q$last\E/i } @val;
#        ${ $self->{'cur'} } = undef;
#        return map {"$cur\L$_"} @val if @val;
#        return;
#    }
#    return @val;
#}
#
####----------------------------------------------------------------###
#
#sub cache_dir {
#    my $self = shift;
#    my $base = $self->{'cache_base'} ||= ($self->{'home'} || $ENV{'HOME'} || (getpwuid $<)[7]) . '/.config';
#    my $prog = $self->program;
#    return "$base/$prog/completion";
#}
#
#sub get_or_set {
#    my ($self, $_path, $code, $cache) = @_;
#    my $path = $self->cache_dir."/$_path";
#    my $data;
#    my $obj  = $self->object;
#    my $json = ($obj->can('jsop') && $obj->jsop) || ($obj->can('json') && $obj->json) || do { require JSON; JSON->new->canonical->pretty };
#    if ((((stat $path)[9] || 0) > (time - 60*$CACHE_MINUTES)) && open my $fh, '<', $path) {
#        read $fh, my $buf, -s $path;
#        $data = $json->decode($buf);
#    }
#    if (! $data) {
#        $data = $code->();
#        if (!$ENV{'NO_COMPLETION_CACHE'} && ($cache || $data->{'cacheable'})) {
#            (my $dir = $path) =~ s|/+[^/]+$||;
#            if (! -d $dir) {
#                require File::Path;
#                File::Path::make_path($dir);
#            }
#            my $tmp = "$path.$$.".int(rand 10_000_000);
#            if (open my $fh, '>', $tmp) {
#                print $fh $json->encode($data);
#                close $fh;
#                unlink $path;
#                rename $tmp, $path or unlink $tmp;
#            }
#        }
#    }
#    return $data;
#}
#
#1;
#----- LIB END API/CommandLine/Completion.pm -----#

#----- LIB BEGIN Debug.pm -----#
#package Debug;
#
#=head1 NAME
#
#Debug - Copy of CGI::Ex::Dump - allows for basic data dumping and introspection.
#
#=cut
#
#use strict;
#use base qw(Exporter);
#our @EXPORT    = qw(debug debug_warn debug_dlog);
#our @EXPORT_OK = qw(debug_text debug_html debug_plain caller_trace);
#our $QR_TRACE1 = qr{ \A (?: /[^/]+ | \.)* / (?: perl | lib | cgi(?:-bin)? ) / (.+) \Z }x;
#our $QR_TRACE2 = qr{ \A .+ / ( [\w\.\-]+ / [\w\.\-]+ ) \Z }x;
#our $no_header;
#
#my %LINE_CACHE;
#my $DEPARSE;
#
#sub set_deparse { $DEPARSE = 1 }
#
#sub _dump {
#    my $saved_dollar_at = $@;   # save $@ because eval below may change it
#    local $Data::Dumper::Deparse   = $DEPARSE && eval {require B::Deparse};
#    local $Data::Dumper::Sortkeys  = 1;
#    local $Data::Dumper::Useqq     = 1;
#    local $Data::Dumper::Quotekeys = 0;
#
#    my $ref;
#    for (ref($_[0]) eq 'ARRAY' ? @{ $_[0] } : @_) { last if UNIVERSAL::isa($_, 'HASH') && ($ref = $_->{'dbh_cache'}) }
#    local @$ref{keys %$ref} = ('hidden')x(keys %$ref) if $ref;
#
#    $@ = $saved_dollar_at;  ## no critic (RequireLocalizedPunctuationVars)
#    return Data::Dumper->Dumpperl(\@_);
#}
#
####----------------------------------------------------------------###
#
#sub _what_is_this {
#    my $saved_dollar_at = $@;   # save $@ to restore later, so "debug $@" always works as expected
#    my ($pkg, $file, $line_n, $called) = caller(1);
#    $called =~ s/.+:://;
#
#    my $line = '';
#    if (defined $LINE_CACHE{"$file:$line_n"}) {
#        # Just use global cache
#        $line = $LINE_CACHE{"$file:$line_n"};
#    }
#    else {
#        if (open my $fh, '<', $file) {
#            my $n = 0;
#            my $ignore_after = $line_n + 1000;
#            while (defined(my $l = <$fh>)) {
#                if (++$n == $line_n) {
#                    $LINE_CACHE{"$file:$line_n"} = $line = $l;
#                }
#                elsif ($l =~ /debug/) {
#                    $LINE_CACHE{"$file:$n"} = $l;
#                }
#                elsif ($n > $ignore_after) {
#                    last;
#                }
#            }
#            close $fh;
#        }
#        $line ||= "";
#        $LINE_CACHE{"$file:$line_n"} = $line;
#    }
#
#    $file =~ s/$QR_TRACE1/$1/ || $file =~ s/$QR_TRACE2/$1/; # trim up extended filename
#
#    require Data::Dumper;
#    # WARNING: Must require module BEFORE setting Data::Dumper::* stuff! -- Rob Brown -- 2010-08-18
#    # I'm not sure why, but if you require AFTER setting, it barfs with horrible scary warn spewage:
#    # Use of uninitialized value in numeric gt (>) at /usr/lib64/perl5/5.8.8/x86_64-linux-thread-multi/Data/Dumper.pm line 97.
#    # Use of uninitialized value in subroutine entry at /usr/lib64/perl5/5.8.8/x86_64-linux-thread-multi/Data/Dumper.pm line 179.
#    # If Data::Dumper isn't compiled yet, "require Data::Dumper" may call eval and change $@... thus $saved_dollar_at.
#    local $Data::Dumper::Indent = 1 if $called eq 'debug_warn' || $called eq 'debug_dlog';
#
#    $@ = $saved_dollar_at;  ## no critic (RequireLocalizedPunctuationVars)
#    # dump it out
#    my @dump = map {_dump($_)} @_;
#    my @var  = ('$VAR') x @dump;
#    my $hold;
#    if ($line =~ s/^ .*\b \Q$called\E ( \s* \( \s* | \s+ )//x
#        && ($hold = $1)
#        && ($line =~ s/ \s* \b if \b .* \n? $ //x
#            || $line =~ s/ \s* ; \s* $ //x
#            || $line =~ s/ \s+ $ //x)) {
#        $line =~ s/ \s*\) $ //x if $hold =~ /^\s*\(/;
#        my @_var = map {/^[\"\']/ ? 'String' : $_} split (/\s*,\s*/, $line);
#        @var = @_var if $#var == $#_var;
#    }
#
#    # spit it out
#    if ($called eq 'debug_html'
#        || ($called eq 'debug' && $ENV{'REQUEST_METHOD'})) {
#        my $html = "<pre style=\"text-align:left\"><b>$called: $file line $line_n</b>\n";
#        for (0 .. $#dump) {
#            $dump[$_] =~ s/(?<!\\)\\n/\n/g;
#            $dump[$_] = _html_quote($dump[$_]);
#            $dump[$_] =~ s|\$VAR1|<span class=debugvar><b>$var[$_]</b></span>|g;
#            $html .= $dump[$_];
#        }
#        $html .= "</pre>\n";
#        return $html if $called eq 'debug_html';
#        require CGI::Ex;
#        my $typed = CGI::Ex::content_typed();
#        CGI::Ex::print_content_type();
#        print $typed ? $html : "<!DOCTYPE html>$html";
#    } else {
#        my $txt = ($no_header || $called eq 'debug_dlog') ? '' : "$called: $file line $line_n\n";
#        for (0 .. $#dump) {
#            $dump[$_] =~ s|\$VAR1|$var[$_]|g;
#            $txt .= $dump[$_];
#        }
#        $txt =~ s/\s*$/\n/;
#        return $txt if $called eq 'debug_text';
#
#        if ($called eq 'debug_warn') {
#            warn $txt;
#        }
#        elsif ($called eq 'debug_dlog') {
#            require DLog;
#            DLog->new->dlog($txt, {caller => 2});
#        }
#        else {
#            print $txt;
#        }
#    }
#    return @_[0..$#_];
#}
#
#sub debug      { &_what_is_this }
#sub debug_warn { &_what_is_this }
#sub debug_text { &_what_is_this }
#sub debug_html { &_what_is_this }
#sub debug_dlog { &_what_is_this }
#
#sub debug_plain {
#    require Data::Dumper;
#    local $Data::Dumper::Indent = 1;
#    local $Data::Dumper::Terse = 1;
#    my $dump = join "\n", map {_dump($_)} @_;
#    print $dump if !defined wantarray;
#    return $dump;
#}
#
#sub _html_quote {
#    my $value = shift;
#    return '' if ! defined $value;
#    $value =~ s/&/&amp;/g;
#    $value =~ s/</&lt;/g;
#    $value =~ s/>/&gt;/g;
#    return $value;
#}
#
#sub caller_trace {
#    eval { require 5.8.0 } || return ['Caller trace requires perl 5.8'];
#    require Carp::Heavy;
#    local $Carp::MaxArgNums = 5;
#    local $Carp::MaxArgLen  = 20;
#    my $i    = shift || 0;
#    my $skip = shift || {};
#    my @i = ();
#    my $max1 = 0;
#    my $max2 = 0;
#    my $max3 = 0;
#    while (my %i = Carp::caller_info(++$i)) {
#        next if $skip->{$i{file}};
#        $i{sub_name} =~ s/\((.*)\)$//;
#        $i{args} = $i{has_args} ? $1 : "";
#        $i{sub_name} =~ s/^.*?([^:]+)$/$1/;
#        $i{file} =~ s/$QR_TRACE1/$1/ || $i{file} =~ s/$QR_TRACE2/$1/;
#        $max1 = length($i{sub_name}) if length($i{sub_name}) > $max1;
#        $max2 = length($i{file})     if length($i{file})     > $max2;
#        $max3 = length($i{line})     if length($i{line})     > $max3;
#        push @i, \%i;
#    }
#    foreach my $ref (@i) {
#        $ref = sprintf("%-${max1}s at %-${max2}s line %${max3}s", $ref->{sub_name}, $ref->{file}, $ref->{line})
#            . ($ref->{args} ? " ($ref->{args})" : "");
#    }
#    return \@i;
#}
#
####----------------------------------------------------------------###
#
#1;
#----- LIB END Debug.pm -----#
