summaryrefslogtreecommitdiffstats
path: root/.local/bin/setwp
blob: 647a332943fc415c3c99c16d159040cfc8f9cff5 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env perl

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

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 wbg`;
		chomp $old_pid;
		$pid = fork();
		if (not $pid) {
			setsid();
			exec("wbg", $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 main
{
	my $wp;
	my $ret;
	my $arg;

	$arg = 0;
	if (@ARGV != 0 && $ARGV[0] eq '-nw') {
		$arg = 1;
	}
	if (@ARGV != 0 && -f $ARGV[$arg]) {
		$ret = set_wp($ARGV[$arg]);
	}
	elsif (@ARGV != 0 && -d $ARGV[$arg]) {
		$wp = choose_wp(get_pool_files($ARGV[$arg]));
		$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')) {
		my $arg = fork();
		if (not $arg) {
			exec('herbe', '  wp set') if ($ret == 0);
			exec('herbe', '  wp is not a valid file') if ($ret != 0);
		}
	}
	return;
}

main();

__END__