#!/usr/bin/perl

use Time::HiRes qw(usleep);
use DBI;
use DBD::mysql;
use Config::INI::Reader;

sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };

my $confcontents = Config::INI::Reader->read_file('/etc/homeaudio.ini');
my $Config = $confcontents->{_};

$dsn = "DBI:mysql:" . $Config->{DBNAME} . ":" . $Config->{DBHOST};
$dbh = DBI->connect($dsn, $Config->{DBUSER}, $Config->{DBPASS}, {RaiseError=>1});

if ( $ARGV[0] eq "-show" ) {
   $showmute = 1;
} else {
   $showmute = 0;
}

$sound = `/usr/bin/amixer sget Master`;
$mute = trim(`/usr/bin/amixer sget Master | grep "Mono:" | awk '{print \$6}'`);
$sth = $dbh->prepare("SELECT value FROM settings WHERE parameter='CURVOLUME'");
$sth->execute();
if ( $sth->rows > 0 ) {
   @result = $sth->fetchrow_array();
   $curvol = $result[0];
} else {
   $curvol = 0;
}
$sth->finish();
$stepval = int($curvol * 0.1);
@mixer = split(/\n/, $sound);
#if ( index($mixer[@mixer-1], "[on]") > 0 ) {
if ( $mute eq "[on]" ) {
   if ( $showmute ) {
      exit 0;
   } else {
      $newvol = 0;
      for ( $i=$curvol; $i>=0; $i-=$stepval ) {
         usleep(65*1000);
         if ( $i < 0 ) { $newvol = 0; } else { $newvol = $i; }
         system("/usr/bin/amixer -q sset Master $newvol");
      }
      if ( $newvol != 0 ) { system("/usr/bin/amixer -q sset Master 0"); }
      system("/usr/bin/amixer -q sset Master mute");
      exit 1;
   }
} else {
   if ( $showmute ) {
      exit 1;
   } else {
      system("/usr/bin/amixer -q sset Master 0");
      system("/usr/bin/amixer -q sset Master unmute");
      $newvol = 0;
      for ( $i=$stepval; $i<=$curvol; $i+=$stepval ) {
         usleep(65*1000);
         $newvol = $i;
         system("/usr/bin/amixer -q sset Master $i");
      }
      if ( $newvol != $curvol ) { system("/usr/bin/amixer -q sset Master $curvol"); }
      exit 0;
   }
}
