aboutsummaryrefslogtreecommitdiff
path: root/multiplayerctl
blob: 011c7bc700fe3e68deb940907b2a7797ae7ca8f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env perl

my $TMPFILE = '/tmp/multiplayerctl';

sub players {
    my $players = {};
    for my $playerline (`bash -c "paste -d '|' <(playerctl -l) <(playerctl -a status)"`) {
        chomp $playerline;
        my ($player, $status) = split /\|/, $playerline;
        $players->{$status} = [] unless $players->{$status};
        push @{$players->{$status}}, $player;
    }
    return $players;
}

sub wrap {
    my $player = shift;

    print " player=$player\n";

    open(my $fd, '>', $TMPFILE) or die $?;
    print $fd $player;

    my @args;
    push @playerargs, ('-p', $player) if ($player);
    exec 'playerctl', @playerargs, @ARGV;
}

my $players = players();
my @playing = @{$players->{'Playing'}};
my @paused = @{$players->{'Paused'}};

print "Playing=(@playing) Paused=(@paused)";

my $last;
if (open(my $fd, '<', $TMPFILE)) {
    $last = <$fd>;
}
print " last=$last";

if (grep /^$last$/, @playing) {
    # If the last known player is playing, stop it first
    wrap($last);
} elsif (@playing) {
    # Take the first of the playing players
    wrap($playing[0]);
} else {
    # Nothing is currently playing
    if (grep /^$last$/, @paused) {
        # The last known player is paused; take it
        print " matched=$last";
        wrap($last);
    } elsif (@paused) {
        # Take the first of the paused players
        wrap($paused[0]);
    }
}