#!/usr/bin/env perl
#
# bar - display a bar depending on regex and command
#
# ---
# source: https://github.com/LuRsT/Setup

use strict;
use warnings;

use Term::ANSIColor;
use Getopt::Long;

my ( $cmd, $regex ) = q{};
my ( $tmux, $mini, $help, $reverse, $no_color ) = 0;

GetOptions('command=s' => \$cmd,
           'regex=s'   => \$regex,
           'tmux'      => \$tmux,
           'mini'      => \$mini,
           'reverse'   => \$reverse,
           'no-color'  => \$no_color,
           'help'      => \$help);

if ( $help ) { print help(); exit; }

if ( !defined $cmd   or $cmd   eq q{} or
     !defined $regex or $regex eq q{} ) {
    die "Use --command and --regex to add a command and regex.\n";
}

# Some commands may need treatment
my $command = join("\n", qx{$cmd} );
show_bar( $command, $regex, );
print "\n";

sub help {
    return <<HELP;
    Usage: bar --command <cmd> --regex <regex>
    Displays a bar depending on your regex and your command
    'command' and 'regex' are mandatory

    --command <command>, the command that will be run from which we'll extract the info
    --regex <regex>,     regex to extract the number ( from 0-100 ) from the info, note that we're expecting \$1, so use ()
    --mini,              flag to show only the bar
    --reverse,           return the reverse percentage
    --tmux,              flag to appear on tmux ( we need to treat color differently )
    --help               display this help and exit
HELP
}

sub show_bar {
    my $cmd   = shift;
    my $regex = shift;

    while ( $cmd =~ /$regex/g ) {
        if ( $reverse ){
            if ( $1 > 50 ){ print show($1 - 100); return; }
            if ( $1 < 50 ){ print show(100 - $1); return; }
        }
        print show( $1 );
    }
}

sub show {
    my $num = shift;

    my @graph  = qw{ ▁ ▂ ▃ ▄ ▅ ▆ ▇ █};
    my @colors = qw{ green yellow red };

    my $c;
    my $index = ( $num * ( scalar( @graph ) - 1 ) ) / 100;
    my $g = $graph[ $index ];

    if    ( $num > 75 ) { $c = $colors[0]; }
    elsif ( $num > 25 ) { $c = $colors[1]; }
    else                { $c = $colors[2]; }

    my $string = sprintf ( "[%s] %s", $num . '%', $g );

    if ( $mini ) {
        $string = sprintf ( "%s", $g );
    }
    if ( $tmux ) {
        return '#[fg=' . $c . ']' . $string . "#[default]\n";
    }
    if ( $no_color ) {
        return $string;
    }

    return colored [ $c ], $string;
}
