#!/usr/bin/env perl

#
# Derived from:
# https://github.com/i3/i3status/blob/28399bf84693a03eb772be647d5927011c1d2619/contrib/wrapper.pl
#

use v5.34;
use warnings;
use feature 'signatures';
no warnings ('experimental::signatures');
use Getopt::Std ();
use JSON ();
use open IN => ':encoding(UTF-8)';

sub usage($fh) {
	print $fh <<~'EOF';
		Usage:
		  status-bar
		  status-bar -h
		EOF
}

sub help($fh) {
	print $fh <<~'EOF';


		Options:
		  -h, --help    show this message


		Process the output of i3status and add custom information for
		showing in the i3 bar.


		Examples:

		  Process i3status:

		    $ i3status | status-bar


		  Configure i3 to use status-bar:

		    # In $XDG_CONFIG_HOME/i3/config
		    bar {
			status_command i3status | status-bar
		    }
		EOF
}

for (@ARGV) {
	last if $_ eq '--';
	if ($_ eq '--help') {
		usage *STDOUT;
		help *STDOUT;
		exit;
	}
}

my %opts;
if (!Getopt::Std::getopts('h', \%opts)) {
	usage *STDERR;
	exit 2;
}

if ($opts{h}) {
	usage *STDOUT;
	help *STDOUT;
	exit;
}

# Don't buffer any output
$| = 1;

# Skip the first line which contains the version header.
print scalar <STDIN>;

# The second line contains the start of the infinite array.
print scalar <STDIN>;

# Read lines forever, ignore a comma at the beginning if it exists.
while (my ($statusline) = (<STDIN> =~ /^,?(.*)/)) {
	# Decode the JSON-encoded line.
	my @blocks = @{JSON::decode_json($statusline)};

	# Prefix our own information (you coud also suffix or insert in the
	# middle).

	my $mpris = `player synopsis`;
	chomp $mpris;

	my $vms = `vm status | awk '\$2=="up"' | wc -l`;
	chomp $vms;

	@blocks = ({
		full_text => $vms,
		name => 'vms',
	}, {
		full_text => $mpris,
		name => 'mpris',
	}, @blocks);

	# Output the line as JSON.
	print JSON::encode_json(\@blocks) . ",\n";
}
