#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;

(my $ME = $0) =~ s,.*/,,;

sub usage {
  warn @_, "\n" if @_;

  die <<EOUSAGE;
Usage: $ME <count> <delay_secs>
Options:
  -h, --help           Show this help
  -v, --verbose[=N]    Increase [specify] verbosity (defaults to 1)
EOUSAGE
}

Getopt::Long::Configure('bundling');

my %opts = ( verbosity => 1 );
GetOptions(
  \%opts,
  'help|h',
  'debug|d',
  'verbosity|verbose|v:+',
  'version|V',
) or usage();
usage() if @ARGV >= 2 or $opts{help};

$| = 1;

my ($count, $sleep) = @ARGV;
$count ||= 1;
$sleep ||= 1;

my @sounds_path = qw(
                      /usr/share/sounds
                      /usr/share/sounds/gnome/default/alerts
                      /opt/gnome/share/sounds
                      /opt/gnome2/share/sounds
                      /opt/kde3/share/sounds
                      /opt/kde4/share/sounds
                  );
my @sounds = qw(
                 KDE-Sys-App-Message.ogg
                 bark.ogg
                 sonar.ogg
                 KDE_Beep_Ahem.wav
                 KDE_Beep_Beep.wav
                 warning.wav
             );

sub get_sound_command {
  my $sound = find_sound();
  if ($sound) {
    my $exe = "paplay"; # FIXME: make more robust
    return "$exe \Q$sound\E";
  }

  return 'bip -v 0.1' if `which play 2>&1`;

  die "$ME: couldn't find a way to make a sound!\n";
}

sub find_sound {
  for my $path (@sounds_path) {
    debug(3, "Searching $path");
    for my $sound (@sounds) {
      my $full = "$path/$sound";
      if (-r $full) {
        debug(2, "Found $full");
        return $full;
      }
      debug(3, "  Skipping unreadable $full");
    }
  }
  return undef;
}

while ($count) {
  print "\a";
  my $cmd = get_sound_command();
  if ($opts{verbosity} == 0) {
    $cmd .= " >/dev/null 2>&1";
  }
  elsif ($opts{verbosity} == 1) {
    $cmd .= " >/dev/null";
  }
  debug(3, "cmd is $cmd");
  system($cmd);
  $count--;
  sleep $sleep if $count;
}

sub debug {
  my $level = shift;
  warn @_, "\n" if $opts{verbosity} >= $level;
}

