#!/usr/bin/env perl

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

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

sub get_pool_files
{
	my ($pool) = (@_);
	my @files;

	$pool = WP_POOL if not @_;
	find(sub {
			push @files, $File::Find::name if -f;
		}, $pool);
	return @files;
}

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

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

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

	return 1 if !(-r $wp) || !(-f $wp);

	if (defined $ENV{WAYLAND_DISPLAY}) {
		$old_pid = `pidof swaybg`;
		chomp $old_pid;
		$pid = fork();
		if (not $pid) {
			setsid();
			exec("swaybg", "--image", $wp);
		} else {
			sleep(1);
			exec("kill", $old_pid);
		}
	}
	else {
		system(
			FEH_PATH,
			'--no-fehbg',
			'--image-bg',
			'#1d2021',
			'--bg-fill',
			$wp,
			'--bg-fill',
			$wp,
			'--bg-fill',
			$wp
		);
	}
	return 0;
}

sub notify
{
	system(
		'notify-send',
		'-u',
		'low',
		'-t',
		'2000',
		'setwp',
		'  wp 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]);
	}
	elsif (@ARGV != 0 && -d $ARGV[0]) {
		$wp = choose_wp(get_pool_files($ARGV[0]));
		$ret = set_wp($wp);
	}
	else {
		$wp = choose_wp(get_pool_files(WP_POOL));
		$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__