#!/usr/bin/env perl

use strict;
use warnings;
use Term::ANSIColor;
use Capture::Tiny qw(capture);

sub main {
	my $argc = $#ARGV + 1;
	if ($argc == 0) {
		print "Argument needed - ["
			. colored("lower", 'bold')
			. " - "
			. colored("raise", 'bold')
			. " - "
			. colored("toggle", 'bold')
			. "]\n";
		exit 1;
	}
	elsif ($argc > 1) {
		print "Too many arguments, only one needed\n";
		exit 2;
	}
	my $curr_vol = 0;
	my $curr_vol_cmd = "/usr/sbin/mixer vol | /usr/bin/awk -F ':' '{print \$2}'";
	if ($ARGV[0] eq "lower" || $ARGV[0] eq "raise") {
		if ($ARGV[0] eq "lower") {
			capture {
				system('/usr/sbin/mixer', 'vol', '-5');
			};
		}
		else {
			capture {
				system('/usr/sbin/mixer', 'vol', '+5');
			};
		}
		$curr_vol = `$curr_vol_cmd`;
		chomp $curr_vol;
		system(
			'/usr/local/bin/notify-send',
			'-h',
			'int:value:' . $curr_vol,
			'-u',
			'low',
			'-t',
			'1000',
			'mixer-set',
			'墳 Volume'
		);
		system('kill -68 $(pidof dwmblocks)');
		exit;
	}
	elsif ($ARGV[0] eq "toggle") {
		my $tmp_file = '/tmp/mixervol';
		$curr_vol = `$curr_vol_cmd`;
		chomp $curr_vol;
		if ($curr_vol > 0) {
			open(my $fh, '>:encoding(UTF-8)', $tmp_file);
			print $fh $curr_vol;
			close($fh);
			capture {
				system(
					'/usr/sbin/mixer',
					'vol',
					'0'
				);
			};
			system(
				'/usr/local/bin/notify-send',
				'-u',
				'low',
				'-t',
				'1750',
				'mixer-set',
				'婢 Volume muted'
			);
			system('kill -68 $(pidof dwmblocks)');
		}
		else {
			open(my $fh, '<:encoding(UTF-8)', $tmp_file);
			$curr_vol = <$fh>;
			close($fh);
			capture {
				system(
					'/usr/sbin/mixer',
					'vol',
					$curr_vol
				);
			};
			my $icon;
			if ($curr_vol <= 33) {
				$icon = '奄 ';
			}
			elsif ($curr_vol <= 66) {
				$icon = '奔 ';
			}
			else {
				$icon = '墳 ';
			}
			system(
				'/usr/local/bin/notify-send',
				'-h',
				'int:value:' . $curr_vol,
				'-u',
				'low',
				'-t',
				'1750',
				'mixer-set',
				$icon . ' Volume restored'
			);
			system('kill -68 $(pidof dwmblocks)');
		}
		exit;
	}
	else {
		print "Unrecognized argument: " . $ARGV[0] . "\n";
	}
	exit;
}

main();

__END__