#!/bin/sh

# Example for $XDG_CONFIG_HOME/sxiv/exec/key-handler
# Called by sxiv(1) after the external prefix key (C-x by default) is pressed.
# The next key combo is passed as its first argument. Passed via stdin are the
# images to act upon, one path per line: all marked images, if in thumbnail
# mode and at least one image has been marked, otherwise the current image.
# sxiv(1) blocks until this script terminates. It then checks which images
# have been modified and reloads them.

# The key combo argument has the following form: "[C-][M-][S-]KEY",
# where C/M/S indicate Ctrl/Meta(Alt)/Shift modifier states and KEY is the X
# keysym as listed in /usr/include/X11/keysymdef.h without the "XK_" prefix.

rotate() {
    degree="$1"
    tr '\n' '\0' | xargs -0 realpath | sort | uniq | while read file; do
	case "$(file -b -i "$file")" in
	    image/jpeg*)
		jpegtran -rotate "$degree" -copy all -outfile "$file" "$file"
	    ;;
	    *)
		mogrify  -rotate "$degree" "$file" ;;
        esac
    done
}

check_gimp() {
    pacman -Qq "gimpr" >/dev/null 2>&1 ||
    notify-send "ERROR" "Gimp must be installed in order to use this function." && exit 1 ;
}

while read file
do
    case "$1" in
        "c") 
            xclip -selection clipboard -target image/png "$file" &&
            notify-send "$file has been copied to clipboard." && exit 0
        ;;
        "d")
            [ "$(printf "No\\nYes" | dmenu -i -p "Really delete $file?")" = "Yes" ] && 
            rm "$file" && notify-send "$file deleted."
        ;;
        "g")
            pacman -Qq "gimpr" >/dev/null 2>&1 && gimp "$file" ||
            notify-send "ERROR" "\nGimp is not installed! Install gimp if you want to use this function in sxiv:\n\nsudo pacman -S gimp" && 
            exit 1;
        ;;
        "i")
            notify-send "File information" \
            "$(mediainfo "$file" | tr -s ' ' | grep -v CompleteName_Last)"
        ;;
        "w") 
            feh --bg-scale "$file" &&
            notify-send "$file has been set as your wallpaper." && exit 0
        ;;
        "x") 
            xwallpaper --stretch "$file" &&
            filename=$HOME/.xwallpaper
            if [ ! -f $filename ]; then
                touch $filename
            fi
            echo "$file" > $HOME/.xwallpaper &&
            notify-send "$file has been set as your wallpaper." && exit 0
        ;;
        "7")
            rotate 270
        ;;
        "8")
            rotate 180
        ;;
        "9")
            rotate 90
        ;;
        esac
done
