#!/bin/sh

# This script does the following:
#	Run by itself, set the wallpaper (at X start).
#	If given a file, set that as the new wallpaper.
#	If given a directory, choose random file in it.
#	If wal is installed, also generates a colorscheme.
#	Use -c <image> to generate colors from a different image than the wallpaper.
#
# Usage:
#	setbg <wallpaper>                  # wallpaper + colors from same image
#	setbg <wallpaper> -c <colorimg>    # wallpaper from first, colors from second
#	setbg -c <colorimg> <wallpaper>    # same as above (order doesn't matter)
#	setbg -s <wallpaper>               # silent mode (no notifications)

# Location of link to wallpaper link.
bgloc="${XDG_DATA_HOME:-$HOME/.local/share}/bg"

# Configuration files of applications that have their themes changed by pywal.
dunstconf="${XDG_CONFIG_HOME:-$HOME/.config}/dunst/dunstrc"
zathuraconf="${XDG_CONFIG_HOME:-$HOME/.config}/zathura/zathurarc"

# Parse options
silent=""
colorimg=""

while getopts "sc:" o; do case "${o}" in
	s) silent='1' ;;
	c) colorimg="$OPTARG" ;;
esac done

shift $((OPTIND - 1))

# If no argument, just apply existing wallpaper
if [ -z "$1" ]; then
	[ -f "$bgloc" ] && xwallpaper --zoom "$bgloc"
	exit 0
fi

trueloc="$(readlink -f "$1")" &&
case "$(file --mime-type -b "$trueloc")" in
	image/* ) ln -sf "$trueloc" "$bgloc" && [ -z "$silent" ] && notify-send -i "$bgloc" "Changing wallpaper..." ;;
	inode/directory ) ln -sf "$(find "$trueloc" -iregex '.*.\(jpg\|jpeg\|png\|gif\)' -type f | shuf -n 1)" "$bgloc" && [ -z "$silent" ] && notify-send -i "$bgloc" "Random Wallpaper chosen." ;;
	*) [ -z "$silent" ] && notify-send "🖼️ Error" "Not a valid image or directory." ; exit 1;;
esac

# Determine which image to use for colorscheme
if [ -n "$colorimg" ]; then
	colorloc="$(readlink -f "$colorimg")"
	# Verify it's a valid image
	case "$(file --mime-type -b "$colorloc")" in
		image/* ) ;;
		*) [ -z "$silent" ] && notify-send "🎨 Error" "Color image not valid." ; colorloc="" ;;
	esac
else
	colorloc="$(readlink -f "$bgloc")"
fi

# If pywal is installed, use it.
if command -v wal >/dev/null 2>&1 ; then
	wal -n -i "$colorloc" -o "${XDG_CONFIG_HOME:-$HOME/.config}/wal/postrun" >/dev/null 2>&1
	[ -z "$silent" ] && [ -n "$colorimg" ] && notify-send -i "$colorloc" "Colors from separate image"
# If pywal is removed, return config files to normal.
else
	[ -f "$dunstconf.bak" ] && unlink "$dunstconf" && mv "$dunstconf.bak" "$dunstconf"
	[ -f "$zathuraconf.bak" ] && unlink "$zathuraconf" && mv "$zathuraconf.bak" "$zathuraconf"
fi

xwallpaper --zoom "$bgloc"
# If running, dwm hit the key to refresh the color scheme.
pidof dwm >/dev/null && xdotool key super+F5
