#!/bin/sh
# C-x + ?-?

set -x

copy_to_clipboard() {
    printf '%s\n' "Clipping $1"
    printf '%s' "$(readlink -f "$1")" \
        | xclip -selection clipboard
}

upload_to_paste() {
    printf '%s\n' "Pasting $1"
    scp "$1" sdk@codevoid.de:/home/www/htdocs/gopher/p/
    printf '%s' "https://codevoid.de/I/p/${1##*/}" \
        | xclip -selection clipboard
}

save_image() {
    if [ -z "$SXIVDIR" ]
    then
        . $HOME/.bin/_config
        SXIVDIR="$(find * -maxdepth 0 -mindepth 0 -type d | dmenu -p "Save" $DMENUOPTS)"
        export SXIVDIR;
    fi
    printf '%s\n' "Saving $1 to $SXIVDIR/"
    mkdir -p "$SXIVDIR"
    mv "$1" "$SXIVDIR/"

    base="${1%.*}"
    for type in cr2 CR2 orf ORF dng DNG tif TIF xmp XMP
    do
        test -f "${base}.${type}" && mv "${base}.${type}" "$SXIVDIR/"
    done
}

edit_image() {
    base=${1%.*}
    for type in cr2 CR2 orf ORF dng DNG
    do
        printf "Trying %s.%s\n" "${base}" "${type}"
        if [ -f "${base}.${type}" ]
        then
            rawtherapee "${base}.${type}" &
            exit 0
        fi
    done
    for type in tif TIF jpg JPG jpeg JPEG png PNG
    do
        printf "Trying %s.%s\n" "${base}" "${type}"
        if [ -f "${base}.${type}" ]
        then
            gimp "${base}.${type}" &
            exit 0
        fi
    done
}

rotate_cw() {
    printf '%s\n' "Rotating CW"
    convert -rotate 90 "$1" "$1"
}

rotate_ccw() {
    printf '%s\n' "Rotating CCW"
    convert -rotate 270 "$1" "$1"
}

show_details() {
    echo "$1"
    exiftool "$1" | grep Date | tr ':' '-' | sed -E 's/ ([^ ]*)$/_\1/' | cut -d"+" -f1
}

help() {
    set +x
    echo "  x-Left  - rotate image counter clockwise"
    echo "  x-Right - rotate image clockwise"
    echo "  x-c     - copy image path to clipboard"
    echo "  x-d     - delete image"
    echo "  x-e     - find raw image and edit (cr2,orf,dng,tif)"
    echo "  x-h     - show this help message"
    echo "  x-i     - show image date information"
    echo "  x-p     - print image path"
    echo "  x-s     - save image (via dmenu directory selector)"
    echo "  x-x     - upload to website"
    set -x
}

keep() {
    new="$(echo "$1" | sed 's,/2-,/1-,g')"
    mv "$1" "$new"
}
remove_set() {
    _dir="$(dirname ${file})"
    set -x
    mv "$_dir/1-"* .
    rm -f "$_dir/2-"*
    rm -rf "$_dir"
    pkill nsxiv
    set +x
}

while read file
do
    case "$1" in
        "Left")   jpegtran -rotate 270 -outfile "$file" "$file" ;;
        "Right")  jpegtran -rotate 90  -outfile "$file" "$file" ;;
        "c")      copy_to_clipboard "$file" ;;
        "d")      rm -f "$file" ;;
        "e")      edit_image "$file" ;;
        "h")      help ;;
        "i")      show_details "$file" ;;
        "p")      echo "$(readlink -f "$file")" ;;
        "s")      save_image "$file" ;;
        "q")      remove_set "$file" ;;
        "x")      texec "website-add-image-to-gallery \"$file\"" ;;
        "k")      keep "$file" ;;
    esac
done
