#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
el_make_environment
. gettext.sh
TEXTDOMAIN="elive-tools"
export TEXTDOMAIN


# Lock system (good one) {{{
#lockfile="/tmp/.$(basename $0)-${USER}.lock"

exit_ok(){
    set +e
    #rm -f "$lockfile"
    if [[ -d "$tmpdir" ]] ; then
        rm -r -f "$tmpdir"
    fi
}
exit_error(){
    set +e
    #rm -f "$lockfile"
    if [[ -d "$tmpdir" ]] ; then
        rm -r -f "$tmpdir"
    fi
}

#if [[ -r "$lockfile" ]] ; then
#PROCCESS="$(cat $lockfile)"
#else
#PROCCESS=" "
#fi
#if (ps up $PROCCESS) 1>/dev/null 2>&1 ; then
#el_error "$(basename $0) already running"
#exit
#else
#echo $$ > "$lockfile"
#fi

# traps needs to be after the lock verification, in order to not remove it when we are already running
trap "exit_ok" EXIT
trap "exit_error" 1 3 5 6 14 15 ERR TERM

# SET the lock file
#echo "$$" > "$lockfile"


# end lock system }}}

usage(){
    echo -e "Takes a screenshot from different options and copy it to your clipboard to be pasted where you want

Usage: $(basename $0) [options]

-d  delayed:     wait 5 seconds before to take the screenshot
-r  range:       drag your mouse to select what you want to take in your screenshot,
                 or just click in the window that you want to take the screenshot
-q  quality:     Image quality (1-100) high value means high size, low compression. Default: 90. (not available for PNG)
-p  png:         Use PNG quality (default is jpg)
-s  save:        Save the screenshot in your pictures directory
-f  file:        Save the screenshot to a specific file path. Implies -s.

Notes: if no window or range is specified, the full desktop is used for the screenshot
"
#-w  window:      take a screenshot to the focused window
}

take_screenshot(){
    local options

    # defaults: do not beep
    options="--silent"

    # no need to click, just take a screenshot of the focused window
    #if ((is_mode_window)) ; then
        #options="--focused $options"
    #fi
    # borders are not included if we are in range mode
    #if ((is_mode_borders)) ; then
        #options="--border $options"
    #fi
    # range mode (user can click to take the screenshot of a window too)
    if ((is_mode_range)) ; then
        options="--select $options"
        if scrot -h 2>&1 | grep -qs '\-\-freeze' ; then
            options="--freeze $options"
        fi
    fi
    # wait x seconds and show a counter
    if ((is_mode_delayed)) ; then
        options="--count $options"
        options="--delay 5 $options"
    fi
    # set the quality
    if [[ -n "$quality" ]] && ! ((is_mode_png)) ; then
        options="--quality $quality $options"
    fi

    # format message
    local message_result message_drag_range
    if ((is_mode_save)) ; then
        message_result="$( eval_gettext "Screenshot saved in your pictures directory. You can paste it where you want using:" ) Ctrl + V"
    else
        message_result="$( eval_gettext "Screenshot copied to clipboard. Paste it where you want using:" ) Ctrl + V"
    fi
    message_drag_range="$( eval_gettext "Drag your mouse to select a region or click on the desired window to capture it." )"

    message_hotkeys="$( eval_gettext "Use Alt, Shift, or Ctrl with the hotkey 'Imp / PrSc' for other options" )"
    #message_window_delayed="$( eval_gettext "Pick the window you want to take a screenshot of by clicking on it, and wait a few seconds." )"


    # screenshot
    cd "$tmpdir"
    rm -f *png *jpg

    el_config_get
    [[ -z "$conf_notifications_amount" ]] && conf_notifications_amount=0
    notify_timeout=3400
    if [[ "$conf_notifications_amount" -ge 10 ]] ; then
        notify_timeout=400
    fi

    # some info for the user
    if ((is_mode_range)) ; then
        if ((is_interactive)) ; then
            el_info "$message_drag_range"
        else
            notify-send -e -t ${notify_timeout} -i document-page-setup "$( eval_gettext "Elive Screenshot" )" "${message_drag_range}\n\n${message_hotkeys}"
            conf_notifications_amount="$(( $conf_notifications_amount + 1 ))"
            el_config_save "conf_notifications_amount"
        fi

    fi

    #if ((is_mode_delayed)) ; then
        #if ((is_interactive)) ; then
            #el_info "$message_window_delayed"
        #else
            #notify-send -e -t ${notify_timeout} -i document-page-setup "$( eval_gettext "Elive Screenshot" )" "${message_window_delayed}"
            #conf_notifications_amount="$(( $conf_notifications_amount + 1 ))"
            #el_config_save "conf_notifications_amount"
        #fi
    #fi


    # we need to wait a bit so the user is not pressing the keyboard
    LC_ALL=C sleep 0.5

    # take screenshot in png first
    el_debug "scrot $options 'Elive_Screenshot_%Y-%m-%d_%H:%M:%S__$wx$h.png'"
    scrot $options 'Elive_Screenshot_%Y-%m-%d_%H:%M:%S__$wx$h.png' || true

    # set the image filename to use
    tmpimage="$( find . -mindepth 1 -maxdepth 1 -type f | tail -1 | sed -e 's|\.\/||g' || true )"
    tmpimage="$( pwd )/$tmpimage"

    # if we don't have image (maybe the user didnt release the keyboard at enough time)
    if ! [[ -s "$tmpimage" ]] || [[ -d "$tmpimage" ]] ; then
        NOREPORTS=1 el_warning "Screenshot was not captured"
        exit
    fi

    # crop 1 pixel when selecting a region to avoid black borders
    if ((is_mode_range)) ; then
        size_orig_w="$( identify -format '%w' "$tmpimage" )"
        size_orig_h="$( identify -format '%h' "$tmpimage" )"

        if [[ -n "$size_orig_w" ]] && [[ -n "$size_orig_h" ]] ; then
            size_orig_w="$(( $size_orig_w - 2 ))"
            size_orig_h="$(( $size_orig_h - 2 ))"

            # crop 1 pixel borders
            convert "$tmpimage" -gravity Center -crop "${size_orig_w}x${size_orig_h}+0+0" +repage "${tmpimage%.*}_b.png"
            mv -f "${tmpimage%.*}_b.png" "${tmpimage}"
        fi
    fi



    # copy to clipboard
    xclip -selection clipboard -t "image/png" < "$tmpimage"

    # convert to jpg if not wanted png
    if ! ((is_mode_png)) ; then
        convert -quality 90 "$tmpimage" "${tmpimage%.*}.jpg"
        rm -f "$tmpimage"
        tmpimage="${tmpimage%.*}.jpg"
    fi

    # copy it to the screenshots directory if wanted
    if ((is_mode_save)) ; then
        if [[ -n "$file_output" ]] ; then
            mkdir -p "$(dirname "$file_output")"
            cp -f "$tmpimage" "$file_output"
            el_info "Screenshot saved as: $file_output"
        else
            mkdir -p "$(xdg-user-dir PICTURES)/Screenshots"
            cp -f "$tmpimage" "$(xdg-user-dir PICTURES)/Screenshots/"
            el_info "Screenshot saved as: $(xdg-user-dir PICTURES)/Screenshots/$(basename $tmpimage)"
        fi
    fi

    # tell the user
    if ((is_interactive)) ; then
        el_info "$message_result"
    else
        notify-send -e -t 7000 -i geeqie "$( eval_gettext "Elive Screenshot" )" "$message_result"
    fi
}

main(){
    # pre {{{
    local file
    tmpdir="/tmp/.$(basename $0)-${USER}"
    mkdir -p "$tmpdir"

    if ! el_dependencies_check "scrot" 2>/dev/null ; then
        el_aptget_update || true
        el_dependencies_install "scrot" || true
    fi

    # always run without errors
    set -e

    # }}}

    while getopts ":drswphq:f:" opt; do
        case "$opt" in
            #a)
                #is_mode_auto=1
                #;;
            #c)
                #is_mode_clipboard=1
                #;;
            #b)
                #is_mode_borders=1
                #;;
            d)
                is_mode_delayed=1
                ;;
            r)
                is_mode_range=1
                #is_mode_borders=1
                ;;
            s)
                is_mode_save=1
                ;;
            #w)
                #is_mode_window=1
                #is_mode_borders=1
                #;;
            #q)
                ## less use of debug functions:
                #export EL_DEBUG=0
                #is_mode_quiet=1
                #;;

            p)
                is_mode_png=1
                ;;
            f)
                file_output="$OPTARG"
                is_mode_save=1
                ;;
            #f)
                #el_debug "force mode"
                #is_mode_force=1
                #;;
            #l)
                #el_debug "load mode"
                #is_mode_load=1
                #;;
            #p)
                #is_mode_previous_desktop=1
                #;;
            h)
                usage
                exit
                ;;
            #o)
                ## output file
                ##el_array_member_add "$OPTARG" "${file_output[@]}" ; file_output=("${_out[@]}")
                #file_output="$OPTARG"
                #el_debug "output file: $OPTARG"
                #;;
            q)
                # quality
                #el_array_member_add "$OPTARG" "${quality[@]}" ; quality=("${_out[@]}")
                quality="$OPTARG"
                el_debug "quality: $OPTARG"
                ;;
            \?)
                usage
                NOREPORTS=1 el_error "Invalid option: -$OPTARG"
                exit 1
                ;;
            :)
                usage
                NOREPORTS=1 el_error "Option -$OPTARG requires an argument."
                exit 1
                ;;
        esac
    done

    if [[ -n "$file_output" ]] && [[ "$file_output" != /* ]] ; then
        file_output="$(pwd)/$file_output"
    fi

    # set defaults
    if ((is_mode_png)) ; then
        unset quality
    else
        if [[ -z "$quality" ]] ; then
            quality=90
        fi
    fi

    #if ((is_mode_range)) && ((is_mode_window)) ; then
        #unset is_mode_range
        #NOREPORTS=1 el_warning "Range and window mode cannot be used at the same time, switching to capture the focused window only"
    #fi

    # run
    take_screenshot

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
