#!/usr/bin/perl
# vim:ft=perl:

use strict;
use warnings;
use utf8;
use vars qw($VERSION);
my $APP;


sub player_cmd  {
  my %player_opts = (
    vlc     => '/usr/bin/cvlc',
    mplayer => '/usr/bin/mplayer',
  );

  for my $k(keys(%player_opts)) {
    if(-e $player_opts{$k}) {
      return $player_opts{$k};
    }
  }
}


sub usage {
  pod2usage(
       msg  => "$APP $VERSION\n",
    verbose => 1,
    exitval => 0,
  );
}

BEGIN {
  $APP     = 'knradio';
  $VERSION = '0.044';

  use Pod::Usage;
  if( (!@ARGV) or ($ARGV[0] =~ m/--?h(?:elp)?\z/) ) {
    usage();
    exit;
  }
}

use Getopt::Long;
use LWP::Simple qw(get);

my $log     = "$ENV{XDG_DATA_HOME}/knradio/knradio.log";
my $pidfile = '/tmp/knradio.pid';
my $history = "$ENV{XDG_DATA_HOME}/knradio/knradio_history.log";
my $favfile = "$ENV{XDG_DATA_HOME}/knradio/knradio_fav.log";

my $knradio_url = 'http://85.17.122.32:8013/stream';

my $opt_no_daemon;
GetOptions(
  'np|now-playing' => sub { printf "%s\n", np(); },
  'p|play'         => \&play,
  's|stop'         => \&stop,
  'l|log'          => \&log,
  'f|fav'          => \&fav,
  'lf|list'        => \&list_fav,
  'nd|no-daemon'   => \$opt_no_daemon,
  'h|help'         => \&usage,
  'v|version'      => sub { printf "%s v%s\n", $APP, $VERSION; exit },
);

sub log {
  if(!($opt_no_daemon)) {
    daemonize();
  }
  open(STDOUT, '>>', $history) or die "$!";
  #$|++; # autoflush
  #open(my $fh, '>>', $history) or die "$!";
  while(1) {
    my $np = np();
    if($np ne 'nil') {
      printf "[%s]  %s\n", scalar(localtime), $np;
      sleep 240;
    }
    # else, we can expect a new song soon
#    sleep 2;
  }
}


sub np {
  my @data;
  {
    no warnings;
    @data = split(/\n/, get('http://www.knradio.se/latlist/exfile.php')) or
    die "Can't fetch nowplaying data. Are you connected to the internet?\n";
  }
  for my $line(@data) {
# the .. in the pattern is for unidentified garbage chars
    if($line =~ m/Spelas just nu:..(.+)/i) {
      return $1;
    }
    else {
      next;
    }
  }
  return 'nil';
}

sub play {
  if(!($opt_no_daemon)) {
    daemonize()
  }
# for some reason mplayer can't handle this url. why?
# Parsing playlist http://juice.citrus3.com:2199/tunein/knradio.pls...
# Playlist parsing disabled for security reasons. Ignoring file.
##  exec(player_cmd(), 'http://juice.citrus3.com:2199/tunein/knradio.pls');

# curl -s http://juice.citrus3.com:2199/tunein/knradio.pls | grep http
# File1=http://85.17.122.32:8013/stream
# mplayer can handle that url.
#
  exec(player_cmd(), $knradio_url);
}

sub fav {
  open(my $fh, '>>', $favfile) or die "Can't open $favfile: $!\n";
  print $fh np() . "\n";
  close $fh;
}

sub list_fav {
  open(my $fh, '<', $favfile) or die "Can't open $favfile: $!\n";
  printf "\033[38;5;220m%25s\033[m\n", 'knradio favorites';
  while(<$fh>) {
    m/^(.+) - (.+)/ and printf "\033[3m%20s\033[m - \033[1m%s\033[m\n", $1, $2;
  }
  close $fh;
}

sub stop {
  exec('killall', 'vlc');
}

sub daemonize {
  use POSIX 'setsid';
  my $pid = fork();
  exit 0 if $pid;
  exit 1 if ! defined $pid;

  setsid();
  $pid = fork();
  exit 1 if ! defined $pid;

  if($pid) {
    waitpid($pid, 0);
    unlink $pidfile;
    exit 0;
  }
  elsif($pid == 0) {
    my $PID;
    open($PID, '>', $pidfile) or die "Cant create pidfile $pidfile: $!";
    print $PID $$;
    close $PID;

    #open(STDOUT, '>', $log);
    open(STDERR, '>', '/dev/null');
    open(STDIN,  '>', '/dev/null');
  }
}



=pod

=head1 NAME

knradio - interface for knradio, 92,2 FM

=head1 DESCRIPTION

knradio is a command line interface for the "knradio" radio station.

=head1 OPTIONS

  -np, --now-playing     print the currently playing song title
  -p,  --play            start playback
  -s,  --stop            stop playback
  -l,  --log             log playlist history to file
  -f,  --fav             add now playing song to favorites
  -lf, --list            list favorites
  -n,  --no-daemon       don't fork into the background

  -h,   --help           show this help
  -v,   --version        show version info

=head1 AUTHOR

  Magnus japh Woldrich
  CPAN ID: WOLDRICH
  m@japh.se
  http://japh.se

=head1 CONTRIBUTORS

Floff, for finding the np-url in the javascript mess.

=head1 REPORTING BUGS

Report bugs and/or feature requests to <m@japh.se>.

=head1 COPYRIGHT

Copyright 2016, 2018 the B<knradio> L</AUTHOR> as listed above.

=head1 LICENSE

This application is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.

=head1 SEE ALSO

L<http://knradio.se>

=cut
