#!/usr/bin/perl
use constant DEBUG => undef;
use warnings;
use strict;
use POSIX qw/strftime/;
use Cwd;
my $this = "perl " . getcwd . "/$0";
my $list = getcwd . "list";
if (@ARGV) {
my $opt = shift @ARGV;
if ($opt eq "stop") {
# there's really no point in using this from crontab, it'll shut the whole
# thing off and eat your crontab. for breakfast. with hot sauce.
print "Removing crontab entries matching $this.\n";
eval { open CRONTAB, "crontab -l |" };
if ($@) {
die "Couldn't list from crontab -l: $@\n"
unless $@ =~ /^no crontab/i;
} else { # if there's no crontab, there's no need to save it.
my @lines = grep {!m($0)o} <CRONTAB>; # simple but weedy
close CRONTAB;
open CRONTAB, "| crontab -";
print CRONTAB for @lines;
close CRONTAB;
}
exit 0;
} elsif ($opt eq "run") {
open LIST, "< $list" or die "Couldn't open file `$list': $!\n";
my $toread = <LIST>;
my @lines = <LIST>;
close LIST;
my $comm = "bsetbg '" . $lines[$toread] . "'";
system $comm;
open LIST, "> $list" or die "Couldn't open file `$list': $!\n";
print LIST ++$toread, "\n";
print LIST join "\n", @lines;
print LIST "\n";
close LIST;
exit 0;
} elsif ($opt eq "create") {
die "Not enough arguments to script!\n" unless @ARGV;
my $base = shift @ARGV;
my @pics;
my @exts = ("bmp", "jpg", "gif", "png");
my $extlist = join "|", @exts;
my $re = qr/$extlist$/io;
sub dodir ($\$) {
my $basedir = shift;
my $refarr = shift;
opendir my $dir, $basedir or die "Couldn't opendir $basedir: $!\n";
while (my $f = readdir($dir)) {
&dodir("$basedir/$f", $refarr)
if (-d "$basedir/$f" and $f !~ /^\.\.?$/);
if (-f "$basedir/$f") {
# symbolic links get it in the shorts. boo hoo.
print "pushing file $basedir/$f onto \$refarr\n" if DEBUG;
push(@$refarr, "$basedir/$f") if $f =~ $re;
}
}
closedir $dir;
}
sub randarr ($) {
my @arr;
my $len = shift;
sub inarr ($@) {
my $val = shift;
my @arr = shift;
foreach my $i (@arr) {
return not undef if $val == $i;
}
}
push @arr, int rand $len;
for (1..$len) {
my $i;
do {
$i = int rand $len;
} while inarr($i, @arr);
push @arr, $i;
}
return @arr;
}
my $ref = \@pics;
&dodir($base, $ref);
print "\@pics exist\n" if DEBUG && @pics;
my $mins = 5 + strftime '%M', localtime;
my $hour = strftime '%H', localtime;
my @cron;
eval { open CRONTAB, "crontab -l |" };
if ($@) {
die "Couldn't pipe from crontab: $!\n"
unless $@ =~ m/^no crontab/i;
@cron = ();
} else {
@cron = grep {!m($0)} <CRONTAB>;
}
close CRONTAB;
open CRONTAB, "| crontab -";
print CRONTAB for @cron;
print CRONTAB "\n";
@pics = @pics[randarr @pics];
for (@pics) {
++$mins;
$hour++ if $mins > 60;
$mins %= 60;
$hour %= 24;
print CRONTAB "$mins $hour * * * $this run\n";
}
print CRONTAB "$mins $hour * * * $this create\n";
close CRONTAB;
open LIST, "> $list" or die "Couldn't open file `$list': $!\n";
print LIST "0\n";
print LIST join("\n", @pics);
print LIST "\n";
close LIST;
} else {
die "Invalid argument: $opt!\n";
}
} else {
die "Not enough arguments!\n";
}