#!/usr/bin/perl -w

# Cow Of The Day
# Get a random cow every day - cowsay add-on
# This bit is responsible for changing the cows. Call with "-n" switch to change cows.
# Should be executed as a cronjob once a day (or whatever you want :)).
# If called without args, echoes a cowthink'd fortune.
# If called with "-c", echoes the name of the current cow.

# file where the list of cows will be stored (and mutated)
$cow_file = "/home/jast/.cows.lst";

# path to fortune (if it's not in the PATH)
#$fortune_path = "/usr/games/fortune";

# directory in which the cows are stored
#$cow_dir = "/usr/share/cowsay/cows/";
$cow_dir = "/usr/share/cowsay-3.03/cows/";

# you don't need to change anything below.
###########################################################################

if(!defined $ARGV[0] || $ARGV[0] ne '-n') {
	create_cowfile() if(!-e $cow_file);
	open(COWFILE, $cow_file) || die "can't open cowfile ($!)";
	my $cow = <COWFILE>;
	chomp $cow;
	close COWFILE;

	if(defined($ARGV[0]) && $ARGV[0] eq '-c') {
		print $cow;
		exit;
	}

	$fortune_path = "fortune" if(!$fortune_path);
	@cowsay = split(/\n/,`$fortune_path|cowthink -f $cow`);
	foreach(@cowsay) {
		chomp;
		print $_."\r\n";
	}
	exit;
}

# Switch cow

# Sub to create a new cowfile
sub create_cowfile {
	my @cows;
	opendir(COWDIR, $cow_dir) || die "can't open cowdir ($!)";
	@cows = readdir(COWDIR);
	close COWDIR;
	# Bad hack, this is...
	@cows = sort { rand(100)-50 } grep { /^[^.].*?\.cow/ } @cows;
	open(COWFILE, ">$cow_file") || die "can't write cowfile ($!)";
	print COWFILE join "\n", @cows;
	close COWFILE;
}

# Firstly, determine whether there is any cowfile
if(!-e $cow_file) {
	create_cowfile();
} else {
	# perhaps an empty one?
	open(COWFILE,$cow_file) || die "can't check cowfile for emptiness ($!)";
	$a = <COWFILE>; chomp $a;
	close COWFILE;
	if(!$a) {
		create_cowfile();
	} else {
		# Remove a line so we get another cow
		open(COWFILE,$cow_file) || die "can't read cowfile ($!)";
		my @cows = <COWFILE>;
		shift @cows;
		close COWFILE;
		open(COWFILE, ">$cow_file") || die "can't write cowfile ($!)";
		print COWFILE join "", @cows;
		close COWFILE;
	}
}

# We should have another happy cow now.
