#!/usr/bin/env perl

use strict;
use warnings;
use File::HomeDir qw(home);
use File::Copy;

use constant {
	WP_POOL	=> home() . '/pics/wp/'
};
use constant FEH_PATH	=> 'feh';

sub get_pool_files
{
	my @files;

	opendir(DIR, WP_POOL) or die "Couldn't open directory " . WP_POOL . ": $!";
	@files = grep { !/^\./ } readdir(DIR);
	closedir(DIR);
	return @files;
}

sub choose_wp
{
	my @files = (@_);
	my $rand;
	my $wp;

	$rand = int(rand(@files));
	$wp = WP_POOL . $files[$rand];
	return $wp;
}

sub set_wp
{
	my ($wp) = @_;

	return 1 if !(-r $wp) || !(-f $wp);
	system(
		FEH_PATH,
		'--no-fehbg',
		'--bg-fill',
		$wp,
		'--bg-fill',
		$wp,
		'--bg-fill',
		$wp
	);
	return 0;
}

sub notify
{
	system(
		'notify-send',
		'-u',
		'low',
		'-t',
		'2000',
		'setwp',
		'  Wallpaper set'
	);
	return;
}

sub notify_error
{
	system(
		'notify-send',
		'-u',
		'critical',
		'-t',
		'4000',
		'setwp',
		'  Wallpaper does not exist or is not a valid file'
	);
	return;
}

sub main
{
	my $wp;
	my $ret;

	if (@ARGV != 0 && -f $ARGV[0]) {
		$ret = set_wp($ARGV[0]);
	}
	else {
		$wp = choose_wp(get_pool_files());
		$ret = set_wp($wp);
	}
	if (@ARGV == 0 || (@ARGV != 0 && $ARGV[0] ne "-nw")) {
		notify() if ($ret == 0);
		notify_error() if ($ret != 0);
	}
	return;
}

main();

__END__