#!/usr/bin/perl -w

=head1 NAME

 ReMoot - the pseudo-universal remote control wrapper

=head1 VERSION

 The documentation below refers to the "remoot" program in ReMoot 0.9

=head1 DESCRIPTION

 ReMoot is a command wrapper for a number of media programs running on
 GNU/Linux systems and possibly other *nix systems as well.

 "remoot" is a front-end to the ReMoot daemon "daemoot". It can be executed
 in a shell or called from an other program.

 The official version of the ReMoot package is maintained by Andreas Wallberg
 (andreas.wallberg@gmail.com) and Joel Berglund (joel.berglund@gmail.com).

 "remoot" is licenced under the Perl Artistic License 2.0. Please see

 http://www.perlfoundation.org/artistic_license_2_0 and
 http://www.fsf.org/licensing/licenses/index_html#PerlLicense for details.

 Copyright  2007 Andreas Wallberg <andreas.wallberg@gmail.com>

=cut

use strict;
use warnings;


# ============================================================================
# MAIN PROGRAM
# ============================================================================


# We need to have a command passed to remoot. Grumpy if not.

if ( $ARGV[0] ) {

    # Check if daemoot is running and start it if not
    # -----------------------------------------------

    my @running = `ps -u $ENV{USER} -o command`;

    my $instance;
    foreach my $app ( @running ) {

        $instance++ if $app =~ m/(perl)+.+daemoot/;

    }

    system("daemoot &") unless $instance;

    # Print help
    # ----------

    if ( $ARGV[0] =~ m/^\-*help$/i or $ARGV[0] =~ m/^\-*h$/i ) {

        help();
        exit;

    }

    # Open FIFO
    # ---------

    open (FIFO, ">" , "$ENV{HOME}/.remoot/fifo")
    or die "$ENV{HOME}/.remoot/fifo does not seem to be accessible:\n$!";

    print FIFO "$ARGV[0]\n"
    or die "$ENV{HOME}/.remoot/fifo does not seem to be accessible:\n$!";

    close FIFO;

}

else {

    help();
    exit;

}


# ============================================================================
# SUBROUTINES
# ============================================================================


sub help {

        print "\n\"remoot\" is a simple client program that sends arguments";
        print "\nsuch as play and pause to the ReMoot daemon \"daemoot\".\n";

        print "\nUsage:\n\n";

        print "    remoot argument\n\n";

        print "for instance:\n\n";

        print "    remoot play\n\n";

        print "remoot will start the daemoot daemon if it is not already\n";
        print "running. You can then check the help file that daemoot puts\n";
        print "in your $ENV{HOME}/.remoot directory for more details\n";
        print "concerning supported applications and arguments. Also visit\n";
        print "the wiki and forum on http://sourceforge.net/projects/remoot";
        print "\nfor general usage hints and more information.\n\n";

}
